Python Quick Reference — 42 Q&A
1. Reverse a String
s = 'hello'
print(s[::-1])
→ Output: olleh
2. Check Palindrome (String)
s = 'madam'
print(s == s[::-1])
→ True means palindrome. Compare string with its reverse.
3. Check Palindrome (Number)
n = 121
print(str(n) == str(n)[::-1])
→ Convert number to string, then compare with reverse.
4. First Non-Repeating Character
s = 'apple'
for ch in s:
if [Link](ch) == 1:
print(ch)
break
→ Output: a — loop through and use count to check frequency.
5. All Substrings of a String
s = 'abc'
for i in range(len(s)):
for j in range(i+1, len(s)+1):
print(s[i:j])
→ Two loops: outer for start index, inner for end index.
6. Check Substring Present
s = 'hello world'
print('world' in s)
→ Use 'in' operator. Returns True if substring exists.
7. Anagram Check
a = 'listen'
b = 'silent'
print(sorted(a) == sorted(b))
→ Sort both strings and compare. True means anagram.
8. Character Frequency Count
s = 'banana'
d = {}
for c in s:
d[c] = [Link](c, 0) + 1
print(d)
→ Use dictionary. [Link](c,0) returns 0 if key not found.
9. Longest Palindromic Substring
s = 'babad'
best = ''
for i in range(len(s)):
for j in range(i+1, len(s)+1):
sub = s[i:j]
if sub == sub[::-1] and len(sub) > len(best):
best = sub
print(best)
→ Check every substring, keep the longest palindrome.
10. Prime Number Check
n = 13
is_prime = n > 1
for i in range(2, int(n**0.5)+1):
if n % i == 0:
is_prime = False
break
print(is_prime)
→ Check divisors from 2 to sqrt(n). No divisor = prime.
11. Perfect Square Check
import math
n = 16
r = [Link](n)
print(r * r == n)
→ 16 -> sqrt=4, 4*4=16 True. 12 -> sqrt=3, 3*3=9 False.
12. Armstrong Number
n = 153
digits = str(n)
total = sum(int(d)**len(digits) for d in digits)
print(total == n)
→ 153 = 1^3 + 5^3 + 3^3 = 153. Output: True.
13. Fibonacci Series
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
→ Each term is sum of previous two. Starts: 0 1 1 2 3 5...
14. Factorial (Recursion)
n = 5
result = 1
for i in range(1, n+1):
result *= i
print(result)
→ Multiply all numbers from 1 to n. 5! = 120.
15. GCD of Two Numbers
a, b = 48, 18
while b:
a, b = b, a % b
print(a)
→ Euclidean algorithm. Replace (a,b) with (b, a%b) until b=0.
16. Even or Odd
n = 7
if n % 2 == 0:
print('Even')
else:
print('Odd')
→ Modulo 2 gives remainder. 0 = even, 1 = odd.
17. All Primes up to N (Sieve)
n = 50
sieve = [True] * (n+1)
sieve[0] = sieve[1] = False
for i in range(2, int(n**0.5)+1):
if sieve[i]:
for j in range(i*i, n+1, i):
sieve[j] = False
print([i for i in range(n+1) if sieve[i]])
→ Mark multiples of each prime as False. Remaining True = primes.
18. Second Largest in List
lst = [3, 1, 4, 1, 5, 9, 2, 6]
unique = list(set(lst))
[Link]()
print(unique[-2])
→ Remove duplicates with set, sort, pick second from last.
19. Reverse a List
lst = [1, 2, 3, 4, 5]
print(lst[::-1])
→ Slicing with step -1 reverses the list.
20. Find Duplicates in List
lst = [1, 2, 3, 2, 4, 3]
seen = set()
dupes = set()
for x in lst:
if x in seen:
[Link](x)
[Link](x)
print(list(dupes))
→ Two sets: one for seen, one to collect duplicates.
21. Most Frequent Element
lst = [1, 3, 2, 3, 4, 3, 2]
print(max(set(lst), key=[Link]))
→ max() with key=[Link] returns element with highest count.
22. Flatten Nested List
nested = [[1,2],[3,[4,5]],6]
result = []
for item in nested:
if isinstance(item, list):
[Link](item)
else:
[Link](item)
print(result)
→ Check if each item is a list; if yes, extend, else append.
23. Rotate List by K
lst = [1,2,3,4,5]
k = 2
lst = lst[k:] + lst[:k]
print(lst)
→ Output: [3,4,5,1,2]. Slice and rejoin.
24. Sort List of Tuples by 2nd Element
pairs = [(1,3),(2,1),(3,2)]
[Link](key=lambda x: x[1])
print(pairs)
→ Lambda key picks index 1 of each tuple for sorting.
25. Transpose a Matrix
m = [[1,2,3],[4,5,6],[7,8,9]]
t = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]
for row in t:
print(row)
→ Swap rows and columns: element at [i][j] moves to [j][i].
26. Matrix Symmetric Check
m = [[1,2,3],[2,5,4],[3,4,6]]
result = all(m[i][j] == m[j][i] for i in range(len(m)) for j in range(len(m)))
print(result)
→ Symmetric means m[i][j] == m[j][i] for all i and j.
27. Matrix Multiplication
A = [[1,2],[3,4]]
B = [[5,6],[7,8]]
R = [[sum(A[i][k]*B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
for row in R:
print(row)
→ R[i][j] = dot product of row i of A with column j of B.
28. Sum of Matrix Diagonals
m = [[1,2,3],[4,5,6],[7,8,9]]
n = len(m)
p = sum(m[i][i] for i in range(n))
s = sum(m[i][n-1-i] for i in range(n))
print('Primary:', p, 'Secondary:', s)
→ Primary: m[i][i]. Secondary: m[i][n-1-i].
29. Bubble Sort
lst = [64,34,25,12,22]
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print(lst)
→ Compare adjacent elements and swap if out of order.
30. Count Word Frequency
sentence = 'the cat sat on the mat'
words = [Link]()
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
print(freq)
→ Split into words, count each using a dictionary.
31. Max Value Key in Dictionary
d = {'a': 3, 'b': 7, 'c': 2}
print(max(d, key=[Link]))
→ max() with key=[Link] compares values, returns the key.
32. Merge Two Dictionaries
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2}
print(merged)
→ ** unpacking merges dicts. d2 values win on key conflict.
33. Common Elements in Two Lists
a = [1,2,3,4,5]
b = [3,4,5,6,7]
print(set(a) & set(b))
→ & gives intersection. | for union, - for difference.
34. Star Triangle Pattern
n = 5
for i in range(1, n+1):
print('*' * i)
→ Row i prints i stars. Simple loop.
35. Pyramid Pattern
n = 5
for i in range(1, n+1):
print(' '*(n-i) + '*'*(2*i-1))
→ Spaces decrease, stars increase. Row i has 2i-1 stars.
36. Floyd's Triangle
n = 5
num = 1
for i in range(1, n+1):
for j in range(i):
print(num, end=' ')
num += 1
print()
→ Sequential numbers filling a triangle row by row.
37. Power Without Built-in
base, exp = 2, 8
result = 1
for _ in range(exp):
result *= base
print(result)
→ Multiply base by itself exp times. Output: 256.
38. Sum of Digits
n = 1234
total = sum(int(d) for d in str(n))
print(total)
→ Convert to string, iterate digits, sum them. Output: 10.
39. Count Vowels in String
s = 'hello world'
count = sum(1 for c in s if c in 'aeiouAEIOU')
print(count)
→ Check each character against vowel set.
40. Remove Duplicates from List
lst = [1,2,2,3,3,4]
result = list(set(lst))
print(result)
→ Convert to set removes duplicates, convert back to list.
41. List Comprehension Squares
squares = [x**2 for x in range(1, 11)]
print(squares)
→ One-liner to create list of squares from 1 to 10.
42. Swap Two Variables
a, b = 5, 10
a, b = b, a
print(a, b)
→ Python allows tuple swap without temp variable. Output: 10 5.