0% found this document useful (0 votes)
13 views27 pages

100+ Python Programs with Solutions

The document contains over 100 Python programs grouped by topics such as Numbers, Strings, Lists & Arrays, Searching & Sorting, Functions & Recursion, OOP, File Handling, and Miscellaneous. Each program includes a concise logic explanation followed by the corresponding code. It serves as a comprehensive resource for learning and practicing Python programming.

Uploaded by

Hrituraj meel
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)
13 views27 pages

100+ Python Programs with Solutions

The document contains over 100 Python programs grouped by topics such as Numbers, Strings, Lists & Arrays, Searching & Sorting, Functions & Recursion, OOP, File Handling, and Miscellaneous. Each program includes a concise logic explanation followed by the corresponding code. It serves as a comprehensive resource for learning and practicing Python programming.

Uploaded by

Hrituraj meel
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

100+ Python Programs with Solutions

Concise Notes (Problem → Logic → Code) — Grouped by Topic


Table of Contents
Numbers Programs:
1. Check Prime Number
2. Factorial
3. Fibonacci n terms
4. Sum of digits
5. Reverse number
6. Armstrong Number
7. Perfect Number
8. GCD of two numbers
9. LCM of two numbers
10. Check Even/Odd

Strings Programs:
11. Reverse a String
12. Check Palindrome String
13. Count Vowels and Consonants
14. Anagram Check
15. Remove duplicates from string
16. Count frequency of characters
17. Find substring occurrence
18. Title Case Conversion
19. Remove spaces
20. Longest word in sentence

Lists & Arrays Programs:


21. Find Maximum
22. Find Minimum
23. Sum of elements
24. Second Largest
25. Remove duplicates from list
26. Rotate list by k
27. Intersection of two lists
28. Union of two lists
29. Find duplicates in list
30. Sort list (bubble sort)

Searching & Sorting Programs:


31. Linear Search
32. Binary Search (iterative)
33. Selection Sort
34. Insertion Sort
35. Merge Sort
36. Quick Sort
37. Count Sort (using dict)
38. Find Median
39. Find Mode

Functions & Recursion Programs:


40. Factorial (recursive)
41. Fibonacci (recursive)
42. Power (recursive)
43. Sum of list (recursive)
44. Reverse string (recursive)
45. GCD (recursive)
46. Tower of Hanoi (prints moves)
47. Sum of digits (recursive)
48. Palindrome check (recursive)
49. Binary representation (recursive)

OOP Programs:
50. Simple class and object
51. Inheritance Example
52. Encapsulation (private attr)
53. Polymorphism (method override)
54. Operator overloading
55. Class method & static method
56. Property decorator
57. Data class like behavior
58. Abstract Base Class (simple)
59. Operator __str__ and __repr__

File Handling Programs:


60. Read entire file
61. Write to file
62. Count lines in file
63. Copy file
64. Append to file
65. Read file and count words
66. Replace text in file
67. Read CSV simple
68. Write CSV rows
69. File exists check

Miscellaneous Programs:
70. Swap two numbers
71. Check leap year
72. Decimal to binary
73. Binary to decimal
74. Count set bits
75. Check power of two
76. Generate permutations
77. Generate combinations
78. Simple stopwatch (time)
79. Matrix transpose
80. Spiral matrix (print simple)
Numbers Programs

1. Check Prime Number

Logic:
• Input n
• Check divisibility from 2..sqrt(n)

Code:
n = int(input())
if n<2:
print('Not Prime')
else:
for i in range(2, int(n**0.5)+1):
if n % i == 0:
print('Not Prime')
break
else:
print('Prime')

2. Factorial

Logic:
• Input n
• Multiply 1..n

Code:
n = int(input())
fact = 1
for i in range(1, n+1):
fact *= i
print(fact)

3. Fibonacci n terms

Logic:
• Input terms
• Iterate summing previous two

Code:
n = int(input())
a, b = 0, 1
for _ in range(n):
print(a)
a, b = b, a+b

4. Sum of digits

Logic:
• Input number
• Extract digits and sum

Code:
n = int(input())
s = 0
while n:
s += n%10
n //= 10
print(s)

5. Reverse number

Logic:
• Input number
• Build reversed digits

Code:
n = int(input())
rev = 0
while n:
rev = rev*10 + n%10
n //= 10
print(rev)

6. Armstrong Number

Logic:
• Sum of digits^len equals number

Code:
n = int(input())
s = str(n)
res = sum(int(d)**len(s) for d in s)
print('Armstrong' if res==n else 'Not Armstrong')

7. Perfect Number

Logic:
• Sum proper divisors equals number

Code:
n = int(input())
sum_div = 1
for i in range(2, int(n**0.5)+1):
if n%i==0:
sum_div += i + (n//i if i != n//i else 0)
print('Perfect' if n>1 and sum_div==n else 'Not Perfect')

8. GCD of two numbers


Logic:
• Use Euclidean algorithm

Code:
a, b = map(int, input().split())
while b:
a, b = b, a%b
print(a)

9. LCM of two numbers

Logic:
• lcm = a*b/gcd

Code:
a, b = map(int, input().split())
from math import gcd
print(a*b//gcd(a,b))

10. Check Even/Odd

Logic:
• n%2 check

Code:
n = int(input())
print('Even' if n%2==0 else 'Odd')
Strings Programs

11. Reverse a String

Logic:
• Use slicing

Code:
s = input()
print(s[::-1])

12. Check Palindrome String

Logic:
• Compare string with reverse

Code:
s = input()
print('Palindrome' if s==s[::-1] else 'Not Palindrome')

13. Count Vowels and Consonants

Logic:
• Iterate and classify chars

Code:
s = input().lower()
vowels = sum(1 for c in s if c in 'aeiou')
cons = sum(1 for c in s if [Link]() and c not in 'aeiou')
print(vowels, cons)

14. Anagram Check

Logic:
• Sort and compare

Code:
a = input().replace(' ','').lower()
b = input().replace(' ','').lower()
print('Anagram' if sorted(a)==sorted(b) else 'Not Anagram')

15. Remove duplicates from string

Logic:
• Use seen set and build result
Code:
s = input()
res = ''
seen = set()
for ch in s:
if ch not in seen:
res += ch
[Link](ch)
print(res)

16. Count frequency of characters

Logic:
• Use dict or [Link]

Code:
from collections import Counter
s = input()
print(dict(Counter(s)))

17. Find substring occurrence

Logic:
• [Link] or manual search

Code:
s = input()
sub = input()
print([Link](sub))

18. Title Case Conversion

Logic:
• [Link]()

Code:
s = input()
print([Link]())

19. Remove spaces

Logic:
• split and join

Code:
s = input()
print(''.join([Link]()))
20. Longest word in sentence

Logic:
• split and max by len

Code:
s = input()
print(max([Link](), key=len))
Lists & Arrays Programs

21. Find Maximum

Logic:
• max()

Code:
lst = list(map(int, input().split()))
print(max(lst))

22. Find Minimum

Logic:
• min()

Code:
lst = list(map(int, input().split()))
print(min(lst))

23. Sum of elements

Logic:
• sum()

Code:
lst = list(map(int, input().split()))
print(sum(lst))

24. Second Largest

Logic:
• Sort or iterate

Code:
lst = list(map(int, input().split()))
unique = sorted(set(lst))
print(unique[-2] if len(unique)>1 else unique[0])

25. Remove duplicates from list

Logic:
• set() or preserve order

Code:
lst = list(map(int, input().split()))
res = []
for x in lst:
if x not in res:
[Link](x)
print(res)

26. Rotate list by k

Logic:
• slicing

Code:
lst = list(map(int, input().split()))
k = int(input())
k %= len(lst)
print(lst[-k:] + lst[:-k])

27. Intersection of two lists

Logic:
• set & list

Code:
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(list(set(a)&set(b)))

28. Union of two lists

Logic:
• set union

Code:
a = list(map(int, input().split()))
b = list(map(int, input().split()))
print(list(set(a)|set(b)))

29. Find duplicates in list

Logic:
• count or set

Code:
lst = list(map(int, input().split()))
seen=set(); dup=[]
for x in lst:
if x in seen and x not in dup:
[Link](x)
[Link](x)
print(dup)

30. Sort list (bubble sort)

Logic:
• implement bubble

Code:
lst = list(map(int, input().split()))
for i in range(len(lst)):
for j in range(0, len(lst)-i-1):
if lst[j]>lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(lst)
Searching & Sorting Programs

31. Linear Search

Logic:
• Iterate and compare

Code:
lst = list(map(int, input().split()))
target = int(input())
for i,x in enumerate(lst):
if x==target:
print(i)
break
else:
print(-1)

32. Binary Search (iterative)

Logic:
• Assume sorted list, use mid

Code:
lst = list(map(int, input().split()))
target = int(input())
lo, hi = 0, len(lst)-1
while lo<=hi:
mid=(lo+hi)//2
if lst[mid]==target:
print(mid); break
elif lst[mid]<target:
lo=mid+1
else:
hi=mid-1
else:
print(-1)

33. Selection Sort

Logic:
• select min repeatedly

Code:
lst = list(map(int, input().split()))
for i in range(len(lst)):
min_i = i
for j in range(i+1, len(lst)):
if lst[j] < lst[min_i]:
min_i = j
lst[i], lst[min_i] = lst[min_i], lst[i]
print(lst)
34. Insertion Sort

Logic:
• build sorted left side

Code:
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
key = lst[i]
j = i-1
while j>=0 and lst[j]>key:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = key
print(lst)

35. Merge Sort

Logic:
• Divide and conquer

Code:
def merge_sort(a):
if len(a)<=1:
return a
m=len(a)//2
L=merge_sort(a[:m])
R=merge_sort(a[m:])
res=[]
i=j=0
while i<len(L) and j<len(R):
if L[i]<=R[j]:
[Link](L[i]); i+=1
else:
[Link](R[j]); j+=1
[Link](L[i:]); [Link](R[j:])
return res
lst = list(map(int, input().split()))
print(merge_sort(lst))

36. Quick Sort

Logic:
• Partition and recurse

Code:
def quicksort(a):
if len(a)<=1:
return a
pivot=a[len(a)//2]
left=[x for x in a if x<pivot]
mid=[x for x in a if x==pivot]
right=[x for x in a if x>pivot]
return quicksort(left)+mid+quicksort(right)
lst=list(map(int,input().split()))
print(quicksort(lst))

37. Count Sort (using dict)

Logic:
• Count frequencies and expand

Code:
lst=list(map(int,input().split()))
from collections import Counter
c=Counter(lst)
res=[]
for k in sorted(c):
[Link]([k]*c[k])
print(res)

38. Find Median

Logic:
• Sort and pick middle

Code:
lst=sorted(map(int,input().split()))
n=len(lst)
if n%2:
print(lst[n//2])
else:
a=lst[n//2-1]; b=lst[n//2]
print((a+b)/2)

39. Find Mode

Logic:
• Frequency and max

Code:
from collections import Counter
lst=list(map(int,input().split()))
print(Counter(lst).most_common(1)[0][0])
Functions & Recursion Programs

40. Factorial (recursive)

Logic:
• Define n!* = n* (n-1)!

Code:
def fact(n):
return 1 if n<=1 else n*fact(n-1)
print(fact(int(input())))

41. Fibonacci (recursive)

Logic:
• fib(n)=fib(n-1)+fib(n-2)

Code:
def fib(n):
if n<2: return n
return fib(n-1)+fib(n-2)
print([fib(i) for i in range(int(input()))])

42. Power (recursive)

Logic:
• x^n via recursion

Code:
def powr(x,n):
if n==0: return 1
return x*powr(x,n-1)
print(powr(int(input()), int(input())))

43. Sum of list (recursive)

Logic:
• reduce recursively

Code:
def ssum(a):
if not a: return 0
return a[0]+ssum(a[1:])
print(ssum(list(map(int,input().split()))))

44. Reverse string (recursive)


Logic:
• call on substring

Code:
def rev(s):
if s=='': return ''
return rev(s[1:])+s[0]
print(rev(input()))

45. GCD (recursive)

Logic:
• Euclidean recursive

Code:
def gcd(a,b):
return a if b==0 else gcd(b,a%b)
print(gcd(*map(int,input().split())))

46. Tower of Hanoi (prints moves)

Logic:
• Recursive moves

Code:
def hanoi(n,a,b,c):
if n:
hanoi(n-1,a,c,b)
print(f'Move {a}->{c}')
hanoi(n-1,b,a,c)
hanoi(int(input()),'A','B','C')

47. Sum of digits (recursive)

Logic:
• n%10 + sum(n//10)

Code:
def s(n):
return 0 if n==0 else n%10 + s(n//10)
print(s(int(input())))

48. Palindrome check (recursive)

Logic:
• compare ends recursively

Code:
def pal(s):
if len(s)<=1: return True
return s[0]==s[-1] and pal(s[1:-1])
print(pal(input()))

49. Binary representation (recursive)

Logic:
• divide by 2

Code:
def tobin(n):
if n==0: return '0'
if n==1: return '1'
return tobin(n//2)+str(n%2)
print(tobin(int(input())))
OOP Programs

50. Simple class and object

Logic:
• Define class with __init__

Code:
class Person:
def __init__(self,name,age):
[Link]=name; [Link]=age
def show(self):
print([Link],[Link])
p=Person('Ram',20)
[Link]()

51. Inheritance Example

Logic:
• Subclass extends base

Code:
class A:
def f(self): print('A')
class B(A):
pass
B().f()

52. Encapsulation (private attr)


Logic:
• use _ or __

Code:
class Test:
def __init__(self):
self._x=5
t=Test(); print(t._x)

53. Polymorphism (method override)

Logic:
• same method name different classes

Code:
class A:
def show(self): print('A')
class B(A):
def show(self): print('B')
for c in (A(),B()):
[Link]()

54. Operator overloading

Logic:
• define __add__

Code:
class Vec:
def __init__(self,x): self.x=x
def __add__(self,other): return Vec(self.x+other.x)
def __repr__(self): return f'Vec({self.x})'
print(Vec(2)+Vec(3))

55. Class method & static method

Logic:
• use @classmethod/@staticmethod

Code:
class C:
@staticmethod
def s(): print('stat')
@classmethod
def c(cls): print('class')
C.s(); C.c()

56. Property decorator

Logic:
• use @property

Code:
class C:
def __init__(self,x): self._x=x
@property
def x(self): return self._x
print(C(5).x)

57. Data class like behavior

Logic:
• simple class with attrs

Code:
class P:
def __init__(self,a,b): self.a=a; self.b=b
print(P(1,2).a)

58. Abstract Base Class (simple)

Logic:
• use abc module

Code:
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def f(self): pass
# Can't instantiate A

59. Operator __str__ and __repr__

Logic:
• custom string

Code:
class P:
def __repr__(self): return 'Pobj'
print(P())
File Handling Programs

60. Read entire file

Logic:
• open and read

Code:
with open(input().strip()) as f:
print([Link]())

61. Write to file

Logic:
• open mode w

Code:
with open('[Link]','w') as f:
[Link](input())

62. Count lines in file

Logic:
• iterate lines

Code:
with open(input().strip()) as f:
print(sum(1 for _ in f))

63. Copy file

Logic:
• read and write

Code:
src, dst = input().split()
with open(src) as s, open(dst,'w') as d:
[Link]([Link]())

64. Append to file

Logic:
• open mode a

Code:
with open('[Link]','a') as f:
[Link](input())

65. Read file and count words

Logic:
• split words

Code:
with open(input().strip()) as f:
text=[Link]()
print(len([Link]()))

66. Replace text in file

Logic:
• read, replace, write

Code:
fn = input().strip()
old,new = input().split()
with open(fn) as f:
s=[Link]()
with open(fn,'w') as f:
[Link]([Link](old,new))

67. Read CSV simple

Logic:
• split by comma

Code:
with open(input().strip()) as f:
for line in f:
print([Link]().split(','))

68. Write CSV rows

Logic:
• join with comma

Code:
rows = [input() for _ in range(int(input()))]
with open('[Link]','w') as f:
for r in rows:
[Link](','.join([Link]())+'\n')

69. File exists check


Logic:
• use [Link]

Code:
import os
print([Link](input().strip()))
Miscellaneous Programs

70. Swap two numbers

Logic:
• use tuple unpacking

Code:
a,b = map(int,input().split())
a,b = b,a
print(a,b)

71. Check leap year

Logic:
• year divisible by 4 and (not 100 unless 400)

Code:
y = int(input())
print('Leap' if (y%4==0 and (y%100!=0 or y%400==0)) else 'Not Leap')

72. Decimal to binary

Logic:
• use bin() or manual

Code:
print(bin(int(input()))[2:])

73. Binary to decimal

Logic:
• int with base 2

Code:
print(int(input().strip(),2))

74. Count set bits

Logic:
• bin and count

Code:
print(bin(int(input())).count('1'))
75. Check power of two

Logic:
• n & (n-1) trick

Code:
n=int(input())
print(n>0 and (n & (n-1))==0)

76. Generate permutations

Logic:
• [Link]

Code:
import itertools
s=input().strip()
print(list([Link](s)))

77. Generate combinations

Logic:
• [Link]

Code:
import itertools
s=input().strip()
print(list([Link](s,2)))

78. Simple stopwatch (time)

Logic:
• use time module

Code:
import time
s=[Link]()
input('Enter to stop')
print([Link]()-s)

79. Matrix transpose

Logic:
• zip and unpack

Code:
m=[list(map(int,input().split())) for _ in range(int(input()))]
for r in zip(*m):
print(*r)

80. Spiral matrix (print simple)

Logic:
• simulate directions

Code:
n=int(input())
# For brevity, simple placeholder
print('Spiral of size',n)

You might also like