📄 Need a professional CV? Try our Resume Builder! Get Started

Python Coding Problems - Solutions

In this blog, we explore some common Python coding problems and their solutions. These problems are great for enhancing your problem-solving skills, whether you're preparing for coding interviews or simply looking to practice your Python skills.

January 01, 2025

Python Coding Problems - Solutions

"Practice makes perfect. The more you solve coding problems, the better you become!"

In this blog post, we provide Python solutions to various coding problems. Each problem is followed by a brief explanation and the code required to solve it. Let's dive right in!

1. Reverse a String in Python Without Using Built-in Functions

Problem Description: Write a function to reverse a string without using any built-in reverse functions.

Test Case: Input: "Python"
Output: "nohtyP"

Code:

def reverse_string(s):
    result = ''
    for char in s:
        result = char + result
    return result

print(reverse_string("Python"))  # Output: nohtyP

2. Write a Function to Check if Two Strings are Anagrams

Problem Description: Write a function to determine if two strings are anagrams (contain the same characters in a different order).

Test Case: Input: "listen", "silent"
Output: True

Code:

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)

print(are_anagrams("listen", "silent"))  # Output: True

3. Implement FizzBuzz

Problem Description: Print numbers from 1 to 20. For multiples of 3, print "Fizz", for multiples of 5, print "Buzz", and for multiples of both, print "FizzBuzz".

Test Case: Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz

Code:

for i in range(1, 21):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

4. Find the Largest Element in a List Without Using `max()`

Problem Description: Write a function to find the largest element in a list without using Python's built-in `max()` function.

Test Case: Input: [3, 5, 7, 2, 8]
Output: 8

Code:

def find_max(lst):
    max_val = lst[0]
    for num in lst:
        if num > max_val:
            max_val = num
    return max_val

print(find_max([3, 5, 7, 2, 8]))  # Output: 8

5. Count Occurrences of Each Character in a String

Problem Description: Count the occurrences of each character in a given string and return the result as a dictionary.

Test Case: Input: "hello"
Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

Code:

from collections import Counter

def count_chars(s):
    return Counter(s)

print(count_chars("hello"))  # Output: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

6. Find the First Non-Repeating Character in a String

Problem Description: Write a function to return the first character in a string that does not repeat.

Test Case:

Input: "swiss"  
Output: "w"

Code:

def first_non_repeating(s):
    counts = Counter(s)
    for char in s:
        if counts[char] == 1:
            return char
    return None

print(first_non_repeating("swiss"))  # Output: w
                        

7. Find Duplicates in a List

Problem Description: Identify duplicate elements in a list and return them as a set.

Test Case:

Input: [1, 2, 3, 1, 2, 4]  
Output: {1, 2}

Code:

def find_duplicates(lst):
    seen = set()
    duplicates = set()
    for num in lst:
        if num in seen:
            duplicates.add(num)
        else:
            seen.add(num)
    return duplicates

print(find_duplicates([1, 2, 3, 1, 2, 4]))  # Output: {1, 2}
                        

8. Check if a List is a Palindrome

Problem Description: Write a function to check if a list reads the same forward and backward.

Test Case:

Input: [1, 2, 3, 2, 1]  
Output: True

Code:

def is_palindrome(lst):
    return lst == lst[::-1]

print(is_palindrome([1, 2, 3, 2, 1]))  # Output: True
                        

9. Implement a Binary Search

Problem Description: Implement a binary search function to find the index of a target element in a sorted list.

Test Case:

Input: [1, 2, 3, 4, 5], 3  
Output: 2

Code:

def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(binary_search([1, 2, 3, 4, 5], 3))  # Output: 2
                        

10. Flatten a Nested List

Problem Description: Write a function to flatten a nested list.

Test Case:

Input: [1, [2, [3, 4], 5]]  
Output: [1, 2, 3, 4, 5]

Code:

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

print(flatten([1, [2, [3, 4], 5]]))  # Output: [1, 2, 3, 4, 5]
                        

Nandi Vardhan
Data Scientist, content creator, and passionate educator in the field of machine learning and data science.