Fundamentals 13 min read

12 Essential Python Coding Challenges with Solutions and Explanations

This article presents twelve Python programming exercises covering string manipulation, list handling, regular expressions, binary conversion, and algorithmic sorting, each accompanied by clear explanations and complete code snippets that illustrate how to solve the problems step by step.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
12 Essential Python Coding Challenges with Solutions and Explanations

Question 1

Implement accum(s) so that each character in the input string is repeated a number of times equal to its 1‑based index, the first occurrence is uppercase and the rest are lowercase, and the groups are joined with hyphens (e.g., "abcd" → "A-Bb-Ccc-Dddd").

def accum(s):
    return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))

Question 2

Create get_sum(a, b) that returns the sum of all integers between the smaller and the larger argument inclusive. The solution uses min(), max() and sum() on a range.

def get_sum(a, b):
    return sum(range(min(a, b), max(a, b) + 1))

Question 3

Write duplicate_count(text) to count how many distinct letters (case‑insensitive) appear more than once in the given string.

def duplicate_count(text):
    text = text.lower()
    duplicates = [ch for ch in set(text) if text.count(ch) > 1]
    return len(duplicates)

Question 4

Implement likes(names) that returns a human‑readable sentence describing who likes an item, handling 0, 1, 2, 3, or more names according to the specification.

def likes(names):
    if not names:
        return 'no one likes this'
    if len(names) == 1:
        return f"{names[0]} likes this"
    if len(names) == 2:
        return f"{names[0]} and {names[1]} like this"
    if len(names) == 3:
        return f"{names[0]}, {names[1]} and {names[2]} like this"
    return f"{names[0]}, {names[1]} and {len(names)-2} others like this"

Question 5

Define Descending_Order(num) that rearranges the digits of a non‑negative integer in descending order and returns the resulting integer.

def Descending_Order(num):
    return int(''.join(sorted(str(num), reverse=True)))

Question 6

Write namelist(names) which receives a list of dictionaries with a name key and returns a string of the names separated by commas, using an ampersand before the last name (or returning an empty string for an empty list).

def namelist(names):
    if not names:
        return ''
    if len(names) == 1:
        return names[0]['name']
    return '{} & {}'.format(', '.join(d['name'] for d in names[:-1]), names[-1]['name'])

Question 7

Implement printer_error(s) that calculates the error rate of a printer control string. Characters outside the range a‑m are errors; the function returns a string "errors/length".

import re
def printer_error(s):
    errors = len(re.sub(r'[a-m]', '', s))
    return f"{errors}/{len(s)}"

Question 8

Create add_binary(a, b) that returns the sum of two integers as a binary string.

def add_binary(a, b):
    return bin(a + b)[2:]

Question 9

Write expanded_form(num) that returns the expanded form of a number as a string (e.g., 70304 → "70000 + 300 + 4").

def expanded_form(num):
    digits = str(num)
    parts = []
    for i, d in enumerate(digits):
        if d != '0':
            parts.append(d + '0' * (len(digits) - i - 1))
    return ' + '.join(parts)

Question 10

Implement order_weight(s) that sorts a space‑separated list of numbers by the sum of their digits (the "weight"). Numbers with equal weight are ordered lexicographically as strings.

def order_weight(s):
    return ' '.join(sorted(s.split(), key=lambda x: (sum(int(c) for c in x), x)))

Question 11

Define countBits(n) that returns the number of 1 bits in the binary representation of an unsigned integer.

def countBits(n):
    return bin(n).count('1')

Question 12

Write valid_parentheses(string) that checks whether a string of parentheses is properly balanced.

def valid_parentheses(string):
    cnt = 0
    for ch in string:
        if ch == '(':
            cnt += 1
        elif ch == ')':
            cnt -= 1
        if cnt < 0:
            return False
    return cnt == 0
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

algorithmPythonString Manipulationcoding challenges
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.