0% found this document useful (0 votes)
7 views49 pages

Python Programs List

The document is a comprehensive list of simple Python programs covering various topics including arithmetic operations, string manipulations, array and matrix operations, and checks for prime and Fibonacci numbers. Each program is presented with code snippets and brief descriptions of their functionality. It serves as a practical reference for beginners looking to learn Python programming through examples.

Uploaded by

mdnche1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views49 pages

Python Programs List

The document is a comprehensive list of simple Python programs covering various topics including arithmetic operations, string manipulations, array and matrix operations, and checks for prime and Fibonacci numbers. Each program is presented with code snippets and brief descriptions of their functionality. It serves as a practical reference for beginners looking to learn Python programming through examples.

Uploaded by

mdnche1234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1|Page

Python Simple Programs List

🔹 1. Add Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)

🔹 2. Maximum of Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
print("Max =", a)
else:
print("Max =", b)

🔹 3. Factorial of a Number
n = int(input("Enter number: "))
fact = 1

for i in range(1, n+1):


fact *= i

print("Factorial =", fact)

🔹 4. Simple Interest
p = float(input("Principal: "))
r = float(input("Rate: "))
t = float(input("Time: "))

si = (p * r * t) / 100
print("Simple Interest =", si)

🔹 5. Compound Interest
p = float(input("Principal: "))
r = float(input("Rate: "))
t = float(input("Time: "))

ci = p * (1 + r/100) ** t
print("Compound Interest =", ci)
2|Page

🔹 6. Armstrong Number Check


num = int(input("Enter number: "))
temp = num
sum = 0

while temp > 0:


digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print("Armstrong Number")
else:
print("Not Armstrong")

🔹 7. Area of a Circle
r = float(input("Enter radius: "))
area = 3.14 * r * r
print("Area =", area)

🔹 8. Prime Numbers in an Interval


start = int(input("Start: "))
end = int(input("End: "))

for num in range(start, end+1):


if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num)

🔹 9. Check Prime Number


num = int(input("Enter number: "))

if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime Number")
else:
print("Not Prime")
3|Page

🔹 10. N-th Fibonacci Number


n = int(input("Enter n: "))

a, b = 0, 1
for i in range(n):
a, b = b, a + b

print("Result =", a)

🔹 11. Check Fibonacci Number


num = int(input("Enter number: "))

a, b = 0, 1
found = False

while a <= num:


if a == num:
found = True
break
a, b = b, a + b

if found:
print("Fibonacci Number")
else:
print("Not Fibonacci")

🔹 12. Nth Multiple in Fibonacci Series


n = int(input("Enter n: "))
m = int(input("Enter multiple: "))

a, b = 0, 1
count = 0

while True:
if a % m == 0:
count += 1
if count == n:
print(a)
break
a, b = b, a + b

🔹 13. ASCII Value of Character


ch = input("Enter character: ")
print("ASCII Value =", ord(ch))
4|Page

🔹 14. Sum of Squares (1 to n)


n = int(input("Enter n: "))
sum = 0

for i in range(1, n+1):


sum += i*i

print("Sum =", sum)

🔹 15. Cube Sum (1 to n)


n = int(input("Enter n: "))
sum = 0

for i in range(1, n+1):


sum += i**3

print("Sum =", sum)

Python List / Array Programs

🔹 1. Sum of Array
arr = [1, 2, 3, 4]
print("Sum =", sum(arr))

🔹 2. Largest Element
arr = [10, 20, 5, 40]
print("Largest =", max(arr))

🔹 3. Array Rotation
arr = [1, 2, 3, 4, 5]
d = 2
print(arr[d:] + arr[:d])
5|Page

🔹 4. Reversal Algorithm Rotation


arr = [1, 2, 3, 4, 5]
[Link]()
print(arr)

🔹 5. Split and Add First Part to End


arr = [1, 2, 3, 4, 5]
k = 2
print(arr[k:] + arr[:k])

🔹 6. Remainder of Array Multiplication


arr = [1, 2, 3]
n = 5

mul = 1
for i in arr:
mul *= i

print("Remainder =", mul % n)

🔹 7. Check Monotonic Array


arr = [1, 2, 3, 4]
print(arr == sorted(arr) or arr == sorted(arr, reverse=True))

🔹 8. Interchange First & Last


arr = [1, 2, 3, 4]
arr[0], arr[-1] = arr[-1], arr[0]
print(arr)

🔹 9. Swap Two Elements


arr = [1, 2, 3]
arr[0], arr[1] = arr[1], arr[0]
print(arr)

🔹 10. Length of List


arr = [1, 2, 3]
print(len(arr))
6|Page

🔹 11. Check Element Exists


arr = [1, 2, 3]
print(2 in arr)

🔹 12. Clear List


arr = [1, 2, 3]
[Link]()
print(arr)

🔹 13. Reverse List


arr = [1, 2, 3]
print(arr[::-1])

🔹 14. Sum of List


arr = [1, 2, 3]
print(sum(arr))

🔹 15. Multiply List Elements


arr = [1, 2, 3]
mul = 1
for i in arr:
mul *= i
print(mul)

🔹 16. Smallest Number


arr = [10, 5, 20]
print(min(arr))

🔹 17. Largest Number


arr = [10, 5, 20]
print(max(arr))
7|Page

🔹 18. Second Largest


arr = [10, 20, 5, 30]
[Link]()
print(arr[-2])

🔹 19. N Largest Elements


arr = [10, 20, 5, 30]
n = 2
[Link](reverse=True)
print(arr[:n])

🔹 20. Even Numbers in List


arr = [1, 2, 3, 4]
print([i for i in arr if i % 2 == 0])

🔹 21. Odd Numbers in List


arr = [1, 2, 3, 4]
print([i for i in arr if i % 2 != 0])

🔹 22. Even Numbers in Range


for i in range(1, 21):
if i % 2 == 0:
print(i)

🔹 23. Odd Numbers in Range


for i in range(1, 21):
if i % 2 != 0:
print(i)

🔹 24. Positive Numbers in List


8|Page

arr = [-1, 2, -3, 4]


print([i for i in arr if i > 0])

🔹 25. Negative Numbers in List


arr = [-1, 2, -3, 4]
print([i for i in arr if i < 0])

🔹 26. Positive in Range


for i in range(-5, 6):
if i > 0:
print(i)

🔹 27. Negative in Range


for i in range(-5, 6):
if i < 0:
print(i)

🔹 28. Remove Multiple Elements


arr = [1, 2, 3, 4]
remove = [2, 3]
arr = [i for i in arr if i not in remove]
print(arr)

🔹 29. Remove Empty Lists


arr = [[], [1,2], [], [3]]
arr = [i for i in arr if i]
print(arr)

🔹 30. Copy List


arr = [1, 2, 3]
new = [Link]()
print(new)

🔹 31. Count Occurrences


9|Page

arr = [1, 2, 2, 3]
print([Link](2))

🔹 32. Remove Empty Tuples


arr = [(), (1,2), ()]
arr = [i for i in arr if i]
print(arr)

🔹 33. Print Duplicates


arr = [1,2,2,3,3,4]
dup = []
for i in arr:
if [Link](i) > 1 and i not in dup:
[Link](i)
print(dup)

🔹 34. Cumulative Sum


arr = [1,2,3]
sum = 0
res = []

for i in arr:
sum += i
[Link](sum)

print(res)

🔹 35. Sum of Digits in List


arr = [12, 34]
total = 0

for i in arr:
for d in str(i):
total += int(d)

print(total)

🔹 36. Break List into Chunks


arr = [1,2,3,4,5,6]
n = 2
10 | P a g e

for i in range(0, len(arr), n):


print(arr[i:i+n])

🔹 37. Sort First List using Second


a = ['a','b','c']
b = [2,1,3]

res = [x for _,x in sorted(zip(b,a))]


print(res)

Python Matrix Programs

🔹 1. Add Two Matrices


A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

result = [[0, 0], [0, 0]]

for i in range(2):
for j in range(2):
result[i][j] = A[i][j] + B[i][j]

print(result)

🔹 2. Multiply Two Matrices


A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

result = [[0, 0], [0, 0]]


11 | P a g e

for i in range(2):
for j in range(2):
for k in range(2):
result[i][j] += A[i][k] * B[k][j]

print(result)

🔹 3. Matrix Product (Same as Multiply)


# Same logic as above
print("Use multiplication code")

🔹 4. Adding and Subtracting Matrices


A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

add = [[A[i][j] + B[i][j] for j in range(2)] for i in range(2)]


sub = [[A[i][j] - B[i][j] for j in range(2)] for i in range(2)]

print("Add:", add)
print("Subtract:", sub)

🔹 5. Transpose (Single Line)


A = [[1, 2],
[3, 4]]

transpose = list(zip(*A))
print(transpose)

🔹 6. Create n × n Matrix
12 | P a g e

n = 3

matrix = []

for i in range(n):
row = []
for j in range(n):
[Link](0)
[Link](row)

print(matrix)

🔹 7. Get K-th Column


A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

k = 1 # 0-based index

col = [row[k] for row in A]


print(col)

🔹 8. Vertical Concatenation
A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

result = A + B
print(result)

🔵 Python String Programs

🔹 1. Palindrome Check
13 | P a g e

s = input("Enter string: ")

if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

🔹 2. Symmetrical or Palindrome
s = input("Enter string: ")

mid = len(s)//2
if s[:mid] == s[mid:]:
print("Symmetrical")

if s == s[::-1]:
print("Palindrome")

🔹 3. Reverse Words
s = input("Enter string: ")
print(" ".join([Link]()[::-1]))

🔹 4. Remove i-th Character


s = "hello"
i = 2
print(s[:i] + s[i+1:])

🔹 5. Substring Check
s = "hello world"
sub = "world"

print(sub in s)

🔹 6. Word Frequency
s = "this is is test"
words = [Link]()

freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1

print(freq)
14 | P a g e

🔹 7. Snake to Pascal Case


s = "hello_world"
print("".join([Link]() for word in [Link]("_")))

🔹 8. Length of String (4 ways)


s = "hello"
print(len(s))
print(sum(1 for _ in s))
count = 0
for i in s:
count += 1
print(count)

🔹 9. Even Length Words


s = "this is test code"
for w in [Link]():
if len(w) % 2 == 0:
print(w)

🔹 10. String with All Vowels


s = input("Enter string: ")
v = set("aeiou")

if [Link](set(s)):
print("Contains all vowels")

🔹 11. Matching Characters


s1 = "abc"
s2 = "bcd"

count = 0
for i in s1:
if i in s2:
count += 1

print(count)

🔹 12. Remove Duplicates


s = "hello"
res = ""
15 | P a g e

for i in s:
if i not in res:
res += i

print(res)

🔹 13. Least Frequent Character


from collections import Counter

s = "hello"
freq = Counter(s)
print(min(freq, key=[Link]))

🔹 14. Max Frequency Character


from collections import Counter

s = "hello"
freq = Counter(s)
print(max(freq, key=[Link]))

🔹 15. Special Character Check


s = "hello@123"

for i in s:
if not [Link]():
print("Contains special character")
break

🔹 16. Random String Until Match


import random
import string

target = "hi"

while True:
s = "".join([Link](string.ascii_lowercase) for _ in
range(len(target)))
print(s)
if s == target:
break

🔹 17. Words Greater than k


16 | P a g e

s = "this is python code"


k = 4

for w in [Link]():
if len(w) > k:
print(w)

🔹 18. Split & Join


s = "hello world"
print("-".join([Link]()))

🔹 19. Binary String Check


s = "10101"

if set(s) <= {"0", "1"}:


print("Binary")

🔹 20. Uncommon Words


s1 = "this is test"
s2 = "this is code"

res = set([Link]()) ^ set([Link]())


print(res)

🔹 21. Replace Duplicate Occurrence


s = "hello"
seen = {}

res = ""
for i in s:
if i in seen:
res += "*"
else:
res += i
seen[i] = 1

print(res)
17 | P a g e

🔹 22. Replace Multiple Words with K


s = "this is bad word"
words = ["bad"]

for w in words:
s = [Link](w, "K")

print(s)

🔹 23. Permutation (Inbuilt)


from itertools import permutations

s = "abc"
for p in permutations(s):
print("".join(p))

🔹 24. Check URL


s = "[Link]

if [Link]("http"):
print("URL Found")

🔹 25. Execute String Code


code = "print(5+5)"
exec(code)

🔹 26. Rotate String


s = "hello"
k = 2

print(s[k:] + s[:k])

🔹 27. Recursive Deletion Check


18 | P a g e

s = "abcabc"

while "abc" in s:
s = [Link]("abc", "")

print("Empty" if s == "" else "Not Empty")

🔹 28. Duplicate Characters (Counter)


from collections import Counter

s = "hello"
freq = Counter(s)

for k, v in [Link]():
if v > 1:
print(k)

🔹 29. Replace Substring


s = "hello world"
print([Link]("world", "Python"))

Python Dictionary Programs

🔹 1. Extract Unique Values


19 | P a g e

d = {'a':1, 'b':2, 'c':1}


print(set([Link]()))

🔹 2. Sum of Dictionary Values


d = {'a':10, 'b':20}
print(sum([Link]()))

🔹 3. Remove a Key
d = {'a':1, 'b':2}
[Link]('a')
print(d)

🔹 4. Sort List of Dict (itemgetter)


from operator import itemgetter

data = [{'a':2}, {'a':1}]


print(sorted(data, key=itemgetter('a')))

🔹 5. Sort List of Dict (lambda)


data = [{'a':2}, {'a':1}]
print(sorted(data, key=lambda x: x['a']))

🔹 6. Merge Two Dictionaries


d1 = {'a':1}
d2 = {'b':2}

d = {**d1, **d2}
print(d)

🔹 7. Convert List to Dictionary


keys = ['a','b']
values = [1,2]
20 | P a g e

d = dict(zip(keys, values))
print(d)

🔹 8. Insert at Beginning (OrderedDict)


from collections import OrderedDict

d = OrderedDict({'b':2})
[Link]({'a':1})
print(d)

🔹 9. Check Order using OrderedDict


from collections import OrderedDict

s = "abc"
print(list([Link](s)))

🔹 10. Election Winner


from collections import Counter

votes = ['A','B','A','C','A']
print(Counter(votes).most_common(1))

🔹 11. Append Keys & Values


d = {'a':1}
d['b'] = 2
print(d)

🔹 12. Sort Dictionary


d = {'b':2, 'a':1}
print(dict(sorted([Link]())))

🔹 13. Sort by Values


d = {'a':3, 'b':1}
print(dict(sorted([Link](), key=lambda x: x[1])))
21 | P a g e

🔹 14. Handle Missing Keys


d = {'a':1}
print([Link]('b', 0))

🔹 15. Multiple Inputs in Key


d = {}
d[(1,2)] = "value"
print(d)

🔹 16. Group Anagrams


from collections import defaultdict

words = ['eat','tea','tan']
d = defaultdict(list)

for w in words:
key = ''.join(sorted(w))
d[key].append(w)

print([Link]())

🔹 17. Kth Non-Repeating Character


from collections import OrderedDict

s = "aabbcd"
d = OrderedDict()

for i in s:
d[i] = [Link](i, 0) + 1

res = [k for k,v in [Link]() if v == 1]


print(res[0])

🔹 18. Binary Anagram Check


a = 5
b = 3

print(sorted(bin(a)) == sorted(bin(b)))
22 | P a g e

🔹 19. Largest Anagram Subset


from collections import Counter

words = ['ab','ba','abc']
print(Counter([''.join(sorted(w)) for w in words]))

🔹 20. Remove Duplicate Words


s = "this is is test"
print(" ".join(set([Link]())))

🔹 21. Mirror Characters


import string

s = "abc"
res = ""

for i in s:
res += chr(219 - ord(i))

print(res)

🔹 22. Frequency in List


arr = [1,2,2,3]

freq = {}
for i in arr:
freq[i] = [Link](i, 0) + 1

print(freq)

🔹 23. List of Tuples → Dictionary


t = [('a',1), ('b',2)]
print(dict(t))

🔹 24. Counter Intersection Example


from collections import Counter
23 | P a g e

s1 = "aabb"
s2 = "ab"

print(Counter(s1) & Counter(s2))

🔹 25. Equal Frequency Check


from collections import Counter

s = "aabbcc"
freq = list(Counter(s).values())

print(len(set(freq)) == 1)

🔹 26. Ordered Words


d = {'apple':1, 'bat':2}
print(sorted([Link]()))

🔹 27. Possible Words


from itertools import permutations

chars = "ab"
print(["".join(p) for p in permutations(chars)])

🔹 28. Keys for Value


d = {'a':1, 'b':2}
print([k for k,v in [Link]() if v == 2])

Python Tuple Programs (Advanced)

🔹 1. Find Size of Tuple


t = (1, 2, 3, 4)
print("Size =", len(t))

🔹 2. Max & Min K Elements


24 | P a g e

t = (5, 1, 8, 3, 9)
k = 2

print("Max K:", sorted(t)[-k:])


print("Min K:", sorted(t)[:k])

🔹 3. List of Tuples (Number & Cube)


lst = [1, 2, 3]

res = [(x, x**3) for x in lst]


print(res)

🔹 4. Adding Tuple to List & Vice Versa


lst = [1, 2]
t = (3, 4)

[Link](t)
print(lst)

t = t + tuple(lst)
print(t)

🔹 5. Closest Pair to K-th Index Element


t = (1, 5, 9, 12)
k = 2

target = t[k]
res = min([(x, target) for x in t if x != target],
key=lambda x: abs(x[0] - target))

print(res)

🔹 6. Join Tuples (Same First Element)


t1 = [(1, 2), (2, 3)]
t2 = [(1, 4), (2, 5)]

res = []

for a in t1:
for b in t2:
if a[0] == b[0]:
[Link]((a[0], a[1], b[1]))

print(res)
25 | P a g e

🔹 7. Extract Digits from Tuple List


t = [('a', 1), ('b', 2)]

digits = [x[1] for x in t]


print(digits)

🔹 8. All Pair Combinations


t1 = (1, 2)
t2 = (3, 4)

res = [(a, b) for a in t1 for b in t2]


print(res)

🔹 9. Remove Tuples of Length K


lst = [(1,2), (3,), (4,5,6)]
k = 2

res = [i for i in lst if len(i) != k]


print(res)

🔹 10. Sort by Second Item


lst = [(1,3), (2,1), (4,2)]

print(sorted(lst, key=lambda x: x[1]))

🔹 11. Order Tuples using External List


lst = [(1,'a'), (2,'b'), (3,'c')]
order = [3,1,2]

res = sorted(lst, key=lambda x: [Link](x[0]))


print(res)

🔹 12. Flatten Tuple of List → Tuple


t = ([1,2], [3,4])

res = tuple(i for sub in t for i in sub)


print(res)
26 | P a g e

🔹 13. Nested Tuple → Dictionary


t = (("a",1), ("b",2))

d = {k:v for k,v in t}


print(d)

🔵 Searching Algorithms

🔹 1. Linear Search
arr = [10, 20, 30, 40]
x = 30

for i in range(len(arr)):
if arr[i] == x:
print("Found at index", i)

🔹 2. Binary Search (Iterative)


arr = [10, 20, 30, 40]
x = 30

l, r = 0, len(arr)-1

while l <= r:
mid = (l+r)//2
if arr[mid] == x:
print("Found")
break
elif arr[mid] < x:
l = mid+1
else:
r = mid-1

🔹 3. Binary Search (Recursive)


def binary(arr, l, r, x):
if l <= r:
mid = (l+r)//2
if arr[mid] == x:
return mid
elif arr[mid] < x:
27 | P a g e

return binary(arr, mid+1, r, x)


else:
return binary(arr, l, mid-1, x)

arr = [10,20,30,40]
print(binary(arr, 0, len(arr)-1, 30))

🔵 Sorting Algorithms

🔹 4. Bubble Sort
arr = [5, 2, 9, 1]

for i in range(len(arr)):
for j in range(len(arr)-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

print(arr)

🔹 5. Selection Sort
arr = [5, 2, 9, 1]

for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]

print(arr)

🔹 6. Insertion Sort
arr = [5, 2, 9, 1]

for i in range(1, len(arr)):


key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

print(arr)
28 | P a g e

🔹 7. Recursive Insertion Sort


def insertion(arr, n):
if n <= 1:
return
insertion(arr, n-1)
last = arr[n-1]
j = n-2
while j >= 0 and arr[j] > last:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = last

arr = [5,2,9,1]
insertion(arr, len(arr))
print(arr)

🔹 8. Merge Sort
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]

merge_sort(L)
merge_sort(R)

i=j=k=0

while i<len(L) and j<len(R):


if L[i] < R[j]:
arr[k]=L[i]; i+=1
else:
arr[k]=R[j]; j+=1
k+=1

while i<len(L):
arr[k]=L[i]; i+=1; k+=1
while j<len(R):
arr[k]=R[j]; j+=1; k+=1

arr=[5,2,9,1]
merge_sort(arr)
print(arr)

🔹 9. Quick Sort
def quick(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x <= pivot]
right = [x for x in arr[1:] if x > pivot]
29 | P a g e

return quick(left) + [pivot] + quick(right)

print(quick([5,2,9,1]))

🔹 10. Heap Sort


import heapq

arr = [5,2,9,1]
[Link](arr)

res = []
while arr:
[Link]([Link](arr))

print(res)

🔹 11. Counting Sort


arr = [1,4,1,2,3]
count = [0]*10

for i in arr:
count[i]+=1

for i in range(len(count)):
while count[i]>0:
print(i)
count[i]-=1

🔹 12. Shell Sort


arr = [5,2,9,1]
gap = len(arr)//2

while gap > 0:


for i in range(gap, len(arr)):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] > temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = temp
gap //= 2

print(arr)

🔹 13. Radix Sort


30 | P a g e

def counting(arr, exp):


n = len(arr)
output = [0]*n
count = [0]*10

for i in arr:
index = i//exp
count[index%10]+=1

for i in range(1,10):
count[i]+=count[i-1]

for i in reversed(arr):
index = i//exp
output[count[index%10]-1]=i
count[index%10]-=1

for i in range(n):
arr[i]=output[i]

def radix(arr):
m = max(arr)
exp = 1
while m//exp > 0:
counting(arr, exp)
exp *= 10

arr=[170,45,75]
radix(arr)
print(arr)

🔹 14. Comb Sort


arr=[5,2,9,1]
gap=len(arr)
shrink=1.3
sorted=False

while not sorted:


gap=int(gap/shrink)
if gap<=1:
gap=1
sorted=True
i=0
while i+gap<len(arr):
if arr[i]>arr[i+gap]:
arr[i],arr[i+gap]=arr[i+gap],arr[i]
sorted=False
i+=1

print(arr)

🔹 15. Gnome Sort


31 | P a g e

arr=[5,2,9,1]
i=0

while i < len(arr):


if i==0 or arr[i]>=arr[i-1]:
i+=1
else:
arr[i],arr[i-1]=arr[i-1],arr[i]
i-=1

print(arr)

🔹 16. Cocktail Sort


arr=[5,2,9,1]
n=len(arr)
swapped=True
start=0
end=n-1

while swapped:
swapped=False
for i in range(start,end):
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
swapped=True
if not swapped:
break
swapped=False
end-=1
for i in range(end-1,start-1,-1):
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
swapped=True
start+=1

print(arr)

🔹 17. Odd-Even Sort


arr=[5,2,9,1]
sorted=False

while not sorted:


sorted=True
for i in range(1,len(arr)-1,2):
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
sorted=False
for i in range(0,len(arr)-1,2):
if arr[i]>arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
sorted=False

print(arr)
32 | P a g e

🔹 18. Bogo Sort 😄


import random

arr=[3,2,1]

def sorted_check(a):
return all(a[i]<=a[i+1] for i in range(len(a)-1))

while not sorted_check(arr):


[Link](arr)

print(arr)

🔹 19. Cycle Sort


arr=[5,2,9,1]

for cycle_start in range(len(arr)-1):


item=arr[cycle_start]
pos=cycle_start

for i in range(cycle_start+1,len(arr)):
if arr[i]<item:
pos+=1

arr[pos],item=item,arr[pos]

print(arr)

🔹 20. Stooge Sort 😅


def stooge(arr,l,h):
if l>=h:
return
if arr[l]>arr[h]:
arr[l],arr[h]=arr[h],arr[l]
if h-l+1>2:
t=(h-l+1)//3
stooge(arr,l,h-t)
stooge(arr,l+t,h)
stooge(arr,l,h-t)

arr=[5,2,9,1]
stooge(arr,0,len(arr)-1)
print(arr)
33 | P a g e

🔷 Pattern Programs

🔹 1. Print Pattern ‘G’


n = 7

for i in range(n):
for j in range(n):
if (i == 0 and j > 0) or \
(i == n//2 and j > 0) or \
(i == n-1 and j > 0) or \
(j == 0 and i != 0 and i != n-1) or \
(j == n-1 and i >= n//2) or \
(i == n//2 and j >= n//2):
print("*", end=" ")
else:
print(" ", end=" ")
print()

🔹 2. Inverted Star Pattern


n = 5

for i in range(n, 0, -1):


print("* " * i)

🔹 3. Double Sided Staircase Pattern


n = 5

for i in range(1, n+1):


print(" "*(n-i) + "* "*i)

for i in range(n-1, 0, -1):


print(" "*(n-i) + "* "*i)

🔹 4. Print with Your Own Font (Custom Text


Pattern)
👉 Example: “HELLO” using stars
34 | P a g e

print("H H EEEEE L L OOO ")


print("H H E L L O O")
print("HHHHH EEEE L L O O")
print("H H E L L O O")
print("H H EEEEE LLLLL LLLLL OOO ")

🕒 Python Date & Time Programs

🔹 1. Get Current Time


from datetime import datetime

now = [Link]()
print("Current Time:", [Link]())

🔹 2. Get Current Date and Time


from datetime import datetime

now = [Link]()
print("Current Date & Time:", now)

🔹 3. Yesterday, Today, Tomorrow


from datetime import datetime, timedelta

today = [Link]()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)

print("Yesterday:", [Link]())
print("Today:", [Link]())
print("Tomorrow:", [Link]())

🔹 4. Convert 12hr → 24hr Format


from datetime import datetime
35 | P a g e

time_12 = "02:30 PM"


time_24 = [Link](time_12, "%I:%M %p")

print(time_24.strftime("%H:%M"))

🔹 5. Time Difference
from datetime import datetime

t1 = [Link]("10:30:00", "%H:%M:%S")
t2 = [Link]("12:00:00", "%H:%M:%S")

diff = t2 - t1
print("Difference:", diff)

🔹 6. Lap Timer ⏱️
import time

input("Press Enter to start")


start = [Link]()

input("Press Enter to stop")


end = [Link]()

print("Elapsed Time:", end - start)

🔹 7. Date String → Timestamp


from datetime import datetime

date_str = "2025-03-01"
dt = [Link](date_str, "%Y-%m-%d")

print("Timestamp:", [Link]())

🔹 8. Timestamp → Datetime
from datetime import datetime

ts = 1700000000
dt = [Link](ts)

print(dt)

🔹 9. Count Days in a Year


36 | P a g e

import calendar

year = 2025
days = {day:0 for day in calendar.day_name}

for month in range(1,13):


cal = [Link](year, month)
for week in cal:
for i, day in enumerate(week):
if day != 0:
days[calendar.day_name[i]] += 1

print(days)

🔵 Python Regex Programs

🔹 1. Only Defined Characters Check


import re

s = "abc123"
pattern = "^[a-zA-Z0-9]+$"

print(bool([Link](pattern, s)))

🔹 2. Count Upper, Lower, Digit, Special


import re

s = "Hello@123"

upper = len([Link](r'[A-Z]', s))


lower = len([Link](r'[a-z]', s))
digit = len([Link](r'[0-9]', s))
special = len([Link](r'[^A-Za-z0-9]', s))
print(upper, lower, digit, special)

🔹 3. Most Occurring Number in String


import re
from collections import Counter

s = "11 22 11 33 11"
nums = [Link](r'\d+', s)

print(Counter(nums).most_common(1))
37 | P a g e

🔹 4. Maximum Number from String


import re

s = "abc 100 xyz 200"


nums = [Link](r'\d+', s)

print(max(map(int, nums)))

🔹 5. Space Before Capital Words


import re

s = "HelloWorldPython"
res = [Link](r'([A-Z])', r' \1', s)

print([Link]())

🔹 6. Starts & Ends Same Character


import re

s = "radar"
print(bool([Link](r'^(.).*\1$', s)))

🔹 7. Upper followed by Lowercase


import re

s = "Hello World"
print([Link](r'[A-Z][a-z]+', s))

🔹 8. Remove Duplicate Words


import re

s = "this is is test test"


res = [Link](r'\b(\w+)( \1\b)+', r'\1', s)
print(res)

🔹 9. Remove All Except Letters & Numbers


import re

s = "abc@123!"
print([Link](r'[^A-Za-z0-9]', '', s))
38 | P a g e

🔹 10. Ends with Alphanumeric


import re

s = "hello123"
print(bool([Link](r'[A-Za-z0-9]$', s)))

🔹 11. Starts with Vowel


import re

s = "apple"
print(bool([Link](r'^[aeiouAEIOU]', s)))

🔹 12. Starts with Substring


import re

s = "hello world"
print(bool([Link](r'^hello', s)))

🔹 13. URL Validation


import re

url = "[Link]
pattern = r'https?://\S+'

print(bool([Link](pattern, url)))

🔹 14. Parse URL


import re

url = "[Link]
res = [Link](r'https?://(www\.)?(\w+)', url)

print(res)

🔹 15. IP Address Validation


import re

ip = "[Link]"
39 | P a g e

pattern = r'^(\d{1,3}\.){3}\d{1,3}$'

print(bool([Link](pattern, ip)))

🔹 16. Email Validation


import re

email = "test@[Link]"
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

print(bool([Link](pattern, email)))

🔹 17. Find Files with Extension


import re

files = ["[Link]", "[Link]", "[Link]"]


res = [f for f in files if [Link](r'\.txt$', f)]

print(res)

🔹 18. Extract IP from Text


import re

text = "IP: [Link]"


print([Link](r'\d+\.\d+\.\d+\.\d+', text))

🔹 19. Password Validity


import re

pwd = "Abc@1234"
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$]).{6,}$'

print(bool([Link](pattern, pwd)))

🔹 20. Strong or Weak Password


40 | P a g e

import re

pwd = "Abc@1234"

if [Link](r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@#$]).{8,}$',
pwd):
print("Strong Password")
else:
print("Weak Password")

🎯 Important Concepts
✔ [Link]() → start check
✔ [Link]() → anywhere check
✔ [Link]() → multiple match
✔ [Link]() → replace

📂 Python File Handling Programs

🔹 1. Read File Word by Word


with open("[Link]", "r") as f:
for line in f:
words = [Link]()
for w in words:
print(w)

🔹 2. Read Character by Character


with open("[Link]", "r") as f:
while True:
ch = [Link](1)
if not ch:
break
print(ch)

🔹 3. Count Characters, Words, Spaces, Lines


41 | P a g e

with open("[Link]", "r") as f:


text = [Link]()

print("Chars:", len(text))
print("Words:", len([Link]()))
print("Spaces:", [Link](" "))
print("Lines:", [Link]("\n") + 1)

🔹 4. Count Key Occurrence


word = "python"

with open("[Link]", "r") as f:


text = [Link]()

print([Link](word))

🔹 5. Find n-length Words


n = 4

with open("[Link]", "r") as f:


for word in [Link]().split():
if len(word) == n:
print(word)

🔹 6. Line Number of Word


word = "python"

with open("[Link]", "r") as f:


for i, line in enumerate(f, 1):
if word in line:
print("Found in line", i)

🔹 7. Count Lines
with open("[Link]", "r") as f:
print(len([Link]()))

🔹 8. Remove Lines Starting with Prefix


prefix = "Hi"

with open("[Link]", "r") as f:


lines = [Link]()
42 | P a g e

with open("[Link]", "w") as f:


for line in lines:
if not [Link](prefix):
[Link](line)

🔹 9. Remove Duplicate Lines


with open("[Link]", "r") as f:
lines = [Link]()

unique = list(set(lines))

with open("[Link]", "w") as f:


[Link](unique)

🔹 10. Read List of Dictionaries


import json

with open("[Link]", "r") as f:


data = [Link](f)

print(data)

🔹 11. Append One File to Another


with open("[Link]", "r") as f1, open("[Link]", "a") as f2:
[Link]([Link]())

🔹 12. Copy Odd Lines


with open("[Link]", "r") as f1, open("[Link]", "w") as f2:
for i, line in enumerate(f1, 1):
if i % 2 != 0:
[Link](line)

🔹 13. Merge Two Files


with open("[Link]") as a, open("[Link]") as b, open("[Link]","w")
as c:
[Link]([Link]() + [Link]())

🔹 14. Reverse Single Line


43 | P a g e

with open("[Link]", "r") as f:


line = [Link]()

print(line[::-1])

🔹 15. Reverse File Content


with open("[Link]", "r") as f:
text = [Link]()

with open("[Link]", "w") as f:


[Link](text[::-1])

🔹 16. Reverse Using Stack


stack = []

with open("[Link]", "r") as f:


for ch in [Link]():
[Link](ch)

with open("[Link]", "w") as f:


while stack:
[Link]([Link]())

🎯 Important Concepts
✔ open() → file open
✔ "r", "w", "a" modes
✔ read(), readline(), readlines()
✔ with → auto close file
44 | P a g e

🔴 Advanced Python Programs

🔹 1. Reverse Linked List


class Node:
def __init__(self, data):
[Link] = data
[Link] = None

def reverse(head):
prev = None
curr = head
while curr:
nxt = [Link]
[Link] = prev
prev = curr
curr = nxt
return prev

🔹 2. Largest Prime Factor


n = 100
i = 2

while i * i <= n:
if n % i:
i += 1
else:
n //= i

print(n)

🔹 3. All Prime Factors


n = 100

for i in range(2, n+1):


while n % i == 0:
print(i)
n //= i

🔹 4. Product of Unique Prime Factors


n = 100
res = 1

for i in range(2, n+1):


45 | P a g e

if n % i == 0:
res *= i
while n % i == 0:
n //= i

print(res)

🔹 5. Sum of Odd Factors


n = 20
sum = 0

for i in range(1, n+1):


if n % i == 0 and i % 2 != 0:
sum += i

print(sum)

🔹 6. Coin Change (Simple)


coins = [1,2,5]
amount = 5

dp = [0]*(amount+1)
dp[0] = 1

for c in coins:
for i in range(c, amount+1):
dp[i] += dp[i-c]

print(dp[amount])

🔹 7. Tower of Hanoi
def hanoi(n, a, b, c):
if n == 1:
print(a, "->", c)
return
hanoi(n-1, a, c, b)
print(a, "->", c)
hanoi(n-1, b, a, c)

hanoi(3, 'A', 'B', 'C')

🔹 8. Sieve of Eratosthenes
n = 50
prime = [True]*(n+1)

for p in range(2, int(n**0.5)+1):


46 | P a g e

if prime[p]:
for i in range(p*p, n+1, p):
prime[i] = False

for i in range(2, n+1):


if prime[i]:
print(i)

🔹 9. Binary Palindrome
n = 9
b = bin(n)[2:]

print(b == b[::-1])

🔹 10. Euclidean Algorithm (GCD)


a, b = 48, 18

while b:
a, b = b, a % b

print(a)

🔹 11. Extended Euclidean


def egcd(a, b):
if b == 0:
return a, 1, 0
g, x1, y1 = egcd(b, a%b)
return g, y1, x1 - (a//b)*y1

print(egcd(48,18))

🔹 12. Max Height (Coins Triangle)


n = 10
h = 0

while n >= h+1:


h += 1
n -= h

print(h)

🔹 13. Min Sum of Factors


47 | P a g e

n = 12
sum = 0

for i in range(1, n+1):


if n % i == 0:
sum += i

print(sum)

🔹 14. Odd-Even Digit Difference


n = 12345
odd = even = 0

for d in str(n):
if int(d)%2:
odd += int(d)
else:
even += int(d)

print(odd - even)

🔹 15. Matrix Z Form


A = [[1,2,3],[4,5,6],[7,8,9]]

for i in range(3):
print(A[0][i], end=" ")
for i in range(1,2):
print(A[i][2-i], end=" ")
for i in range(3):
print(A[2][i], end=" ")

🔹 16. Smallest K Digit Divisible


k = 3
x = 7

num = 10**(k-1)

while True:
if num % x == 0:
print(num)
break
num += 1

🔹 17. Number Series Without Loop


def series(n):
if n == 0:
48 | P a g e

return
print(n)
series(n-1)

series(5)

🔹 18. Triangle Validity


a,b,c = 60,60,60

print(a+b+c == 180 and a>0 and b>0 and c>0)

🔹 19. Most Occurring Character


from collections import Counter

s = "hello"
print(Counter(s).most_common(1))

🔹 20. Sum of Even Factors


n = 20
sum = 0

for i in range(1,n+1):
if n%i==0 and i%2==0:
sum+=i

print(sum)

🔹 21. Digits Divide Number


n = 128

for d in str(n):
if int(d)==0 or n%int(d)!=0:
print("No")
break
else:
print("Yes")

🔹 22. Consecutive 0s in Binary


n = 8
b = bin(n)

print("00" in b)
49 | P a g e

🔹 23. Modular Equation Solutions


a, b, m = 3, 6, 9

count = 0
for x in range(m):
if (a*x) % m == b % m:
count += 1

print(count)

🔹 24. Legendre’s Conjecture (Check)


import math

def is_prime(n):
if n<2: return False
for i in range(2,int([Link](n))+1):
if n%i==0:
return False
return True

n = 10
for i in range(n*n, (n+1)*(n+1)):
if is_prime(i):
print("Prime found:", i)
break

You might also like