Back to Study Material Python

Practice Problems

Solving practice problems is the most effective way to internalize Python. The following problems cover fundamental patterns that appear repeatedly in real...

Practice Problems

Python Practice Problems and Solutions

Solving practice problems is the most effective way to internalize Python. The following problems cover fundamental patterns that appear repeatedly in real codebases and technical interviews.

Problem 1: FizzBuzz Print numbers 1-100. For multiples of 3, print "Fizz". For multiples of 5, print "Buzz". For multiples of both, print "FizzBuzz".

Solution: for n in range(1, 101): if n % 15 == 0: print('FizzBuzz') elif n % 3 == 0: print('Fizz') elif n % 5 == 0: print('Buzz') else: print(n) Key insight: check 15 (both conditions) first; otherwise the elif chain short-circuits.

Problem 2: Flatten a nested list Input: [[1, 2], [3, [4, 5]], 6] Output: [1, 2, 3, 4, 5, 6]

def flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result

Problem 3: Count word frequencies in a string from collections import Counter text = "the cat sat on the mat the cat" freq = Counter(text.split()) print(freq.most_common(3)) # [('the', 3), ('cat', 2), ('sat', 1)]

Problem 4: Find duplicate numbers in a list def find_duplicates(nums): seen = set() dups = set() for n in nums: if n in seen: dups.add(n) seen.add(n) return list(dups)

Problem 5: Reverse a string without slicing def reverse_str(s): result = '' for ch in s: result = ch + result return result # Or more Pythonically: return ''.join(reversed(s))

Problem 6: Check if a string is a palindrome def is_palindrome(s): s = s.lower().replace(' ', '') return s == s[::-1]

Practical tip: Before coding any problem, verbalize the approach. Identify the input type, edge cases (empty input, negative numbers, duplicates), and the simplest correct solution before optimizing.

Exam tip: Python's collections module contains Counter, defaultdict, OrderedDict, and deque, which solve many common algorithm problems more elegantly than manually managing data structures. Mention these in interviews to show library awareness.