Practice: Common Python Programming Problems
Q1. Sum of digits
Write code that prints the sum of the digits of 12345.
Goal: Loop over digits.
Q2. Reverse a string
Print the reverse of 'python'.
Goal: Use slicing.
Q3. Count vowels
Print how many vowels are in 'programming language'.
Goal: Count characters.
Q4. Largest of a list without max
Find the largest value in [4, 19, 7, 3] using a loop and print it.
Goal: Track a running best.
Q5. Character frequency
Print a dictionary with the count of each letter in 'banana', in order of first appearance.
Goal: Count with a dictionary.
Q6. Armstrong number
Print True if 153 equals the sum of each digit raised to the number of digits.
Goal: Combine digits and powers.
Q7. FizzBuzz order
What does this print?
for n in [3, 5, 15, 7]:
if n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
elif n % 15 == 0:
print('FizzBuzz')
else:
print(n)Goal: Condition order.
Q8. Reverse words
What does this print?
print(' '.join('one two three'.split()[::-1]))Goal: Reverse a list.
Q9. Palindrome check
What does this print?
def pal(s):
return s == s[::-1]
print(pal('level'), pal('Level'))Goal: Case matters.
Q10. Set removes order
What does this print?
items = [5, 5, 6, 5, 7]
print(sorted(set(items)), len(set(items)))Goal: Use sets.
Q11. Counter output
What does this print?
from collections import Counter
print(Counter('aabbbc').most_common(1))Goal: Use Counter.
Q12. Fibonacci terms
What does this print?
a, b = 0, 1
for _ in range(6):
a, b = b, a + b
print(a, b)Goal: Trace a loop.
Q13. Palindrome never true
This function should say True for 'noon' but fails for 'Noon'. Fix it.
def pal(s):
return s == s[::-1]
print(pal('Noon'))Goal: Normalise input.
Q14. Off by one
The loop below should print 1 to 5 but stops at 4. Fix it.
for i in range(1, 5):
print(i)Goal: Fix off-by-one.
Q15. Second largest bug
This returns 9 for [5, 9, 9, 7] but the second largest distinct value is 7. Fix it.
nums = [5, 9, 9, 7]
print(sorted(nums)[-2])Goal: Handle duplicates.
Q16. Choose a data structure
You need to remove duplicates from a list but keep the first-seen order. Which approach works and why?
Goal: Pick data structures.
Q17. Why test up to square root
Why does a prime check only need divisors up to the square root of n?
Goal: Explain an optimisation.
Q18. Recursion or loop
Give one reason to prefer a loop for Fibonacci in an interview.
Goal: Compare approaches.