Fundamentals 33 min read

Python Programming Exercises: Narcissistic Numbers, Algorithms, and Common Coding Problems

This article presents a series of Python programming exercises covering topics such as Narcissistic numbers, four‑digit Armstrong numbers, string reversal, number guessing games, classic algorithms like bubble sort, binary search, recursion, palindrome detection, and many other fundamental coding challenges with complete code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Exercises: Narcissistic Numbers, Algorithms, and Common Coding Problems

Problem 1: Narcissistic (Armstrong) Numbers – A Narcissistic number is a three‑digit integer equal to the sum of the cubes of its digits. Example: 153 = 1³ + 5³ + 3³.

for i in range(100, 1000):
    i1 = i // 100  # hundreds
    i2 = i // 10 % 10  # tens
    i3 = i % 10  # units
    if i1 ** 3 + i2 ** 3 + i3 ** 3 == i:
        print(f"{i}是水仙花数")

Problem 2: Four‑Digit Armstrong Numbers – Similar to Problem 1 but for four‑digit numbers, checking if the sum of the fourth powers of each digit equals the number.

for i in range(1000, 10000):
    i1 = i // 1000
    i2 = i // 10 % 10
    i3 = i // 10 % 10
    i4 = i % 10
    if i1 ** 4 + i2 ** 4 + i3 ** 4 + i4 ** 4 == i:
        print(f"{i}是四叶玫瑰数")

Problem 3: Reverse a String – Two methods are shown: slicing and a loop that builds a list of characters in reverse order.

str = input("请输入字符串")
print(str[::-1])
str = input("请输入字符串")
list = []
for x in range(len(str)-1, -1, -1):
    list.append(str[x])
print(''.join(list))

Problem 4: Number Guessing Game – The user has 10 attempts to guess a random integer between 0 and 100, gaining or losing 10 points each round.

import random as rd
number = rd.randint(0, 100)
for i in range(10):
    choice = int(input("请输..."))
    if choice > number:
        print("你猜大了")
    elif choice < number:
        print("你猜小了")
    else:
        print("你猜对了,真棒!")
        break

Problem 5: Hundred Chickens for Hundred Coins – Uses nested loops to find all combinations of roosters, hens, and chicks that satisfy the classic puzzle constraints.

count = 0
for x in range(1, 20):
    for y in range(1, 33):
        z = 100 - x - y
        if z > 0 and 5*x + 3*y + z/3 == 100:
            count += 1
            print(f"第{count}种买法,公鸡买了{x}只,母鸡买了{y}只,小鸡买了{z}只")

Problem 6: Leap Year Checker – Determines whether a given year is a leap year and calculates the day number within the year.

year = int(input("请输入年份"))
month = int(input("请输入月份"))
day = int(input("请输入日期"))
date_list = [31,29,31,30,31,30,31,31,30,31,30,31]
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(f"{year}年是闰年")
else:
    print(f"{year}年是平年")
    date_list[1] = 28
count_day = day
for i in range(month-1):
    count_day += date_list[i]
print(f"{year}年{month}月{day}日是当年的第{count_day}天")

Problem 7: Monkey and Peaches – Uses reverse recursion to compute the original number of peaches based on daily consumption rules.

p = 1
print(f"第10天还剩下{p}个桃子")
for i in range(9,0,-1):
    p = (p + 1) * 2
    print(f"第{i}天还剩下{p}个桃子")
print(f"第一天一共摘了{p}个桃子")

Problem 8: Bubble Sort – Demonstrates the bubble sort algorithm with detailed step‑by‑step swaps and includes a NumPy‑generated random list example.

import numpy as np
pop_list = np.random.randint(100, size=6)
count = len(pop_list)
print('没排序之前的列表', pop_list)
for i in range(count-1):
    for j in range(count-i-1):
        if pop_list[j] > pop_list[j+1]:
            pop_list[j], pop_list[j+1] = pop_list[j+1], pop_list[j]
    print(f'第{i+1}轮排好序是:', pop_list)
print('排好序的列表为', pop_list)

Problem 9: Binary Search – Shows both iterative and recursive implementations to locate a number in a sorted list.

arr_list = [5,7,11,22,27,33,39,52,58]
number = 11
left, right = 0, len(arr_list)-1
count = 0
while left <= right:
    middle = (left + right) // 2
    count += 1
    if number > arr_list[middle]:
        left = middle + 1
    elif number < arr_list[middle]:
        right = middle - 1
    else:
        print(f"数字{number}已找到,索引值为{middle}")
        break
else:
    print(f"数字{number}没有找到")
print(f"一共用了{count}次查找")
def binary_search(number, left, right):
    if left <= right:
        middle = (left + right) // 2
        if number < arr_list[middle]:
            return binary_search(number, left, middle-1)
        elif number > arr_list[middle]:
            return binary_search(number, middle+1, right)
        else:
            return middle
    else:
        return -1
print(binary_search(11, 0, len(arr_list)-1))

Problem 10: Selection Sort – Finds the minimum element repeatedly to sort a list, with a random example.

import random as rd
sec_list = [rd.randint(1,100) for i in range(8)]
length = len(sec_list)
print(f'未排序的列表为:{sec_list}')
for i in range(length-1):
    min_index = i
    for j in range(i+1, length):
        if sec_list[min_index] > sec_list[j]:
            min_index = j
    sec_list[min_index], sec_list[i] = sec_list[i], sec_list[min_index]
    print(f'第{i+1}轮排好序是:{sec_list}')
print(f'最终排好序的列表为:{sec_list}')

Problem 11: Rock‑Paper‑Scissors Game – Implements a scoring system where the player and computer start with 100 points and gain/lose 10 points per round.

import random as rd
game_info = {1:"剪刀",2:"石头",3:"布"}
score = 100
while True:
    robots_choice = rd.randint(1,3)
    user_choice = input("请出拳")
    if user_choice not in '123':
        print('出拳错误,请重新出拳')
        continue
    user_choice = int(user_choice)
    print(f'电脑出{game_info[robots_choice]}')
    print(f'你出{game_info[user_choice]}')
    if (user_choice==1 and robots_choice==3) or (user_choice==2 and robots_choice==1) or (user_choice==3 and robots_choice==2):
        score += 10
        print(f'你赢得本轮游戏,当前分数为{score}')
    elif user_choice == robots_choice:
        print(f'本轮游戏平局,当前分数为{score}')
    else:
        score -= 10
        print(f'你输了本轮游戏,当前分数{score}')
    if score >= 200:
        print('游戏结束,你赢得比赛')
        break
    elif score <= 0:
        print('游戏结束,你输了')
        break

Problem 12: Happy Numbers – Determines whether a number eventually reaches 1 by repeatedly summing the squares of its digits.

def sum_square(n):
    s = 0
    for i in str(n):
        s += int(i) ** 2
    return s
list1 = []
n = int(input('请输入数字:'))
while sum_square(n) not in list1:
    n = sum_square(n)
    list1.append(n)
if n == 1:
    print('是快乐数')
else:
    print('不是快乐数')

Problem 13: Guess Age (Part 1) – Finds two ages whose product is six times their sum and whose difference is less than 8.

for i in range(1,100):
    for j in range(1,i):
        if i*j == 6*(i+j) and i-j < 8:
            print(i,j)
# Output: 15 10

Problem 14: Guess Age (Part 2) – Finds a two‑digit age whose cube is a 4‑digit number and fourth power is a 6‑digit number, together containing each digit 0‑9 exactly once.

for i in range(10,30):
    i3 = str(i**3)
    i4 = str(i**4)
    if len(i3)==4 and len(i4)==6 and len(set(i3+i4))==10:
        print(i)
        print(i3+i4)
# Output: 18

Problem 15: Implementing split() – Provides a custom split function that mimics Python's built‑in split behavior with optional limit.

def split_s(string, sep="", num=0):
    split_words = []
    last_index = 0
    count = 0
    for index, char in enumerate(string):
        if count == num and num > 0:
            split_words.append(string[last_index:len(string)])
            break
        if char == sep:
            split_words.append(string[last_index:index])
            last_index = index + 1
            count += 1
        elif index + 1 == len(string):
            split_words.append(string[last_index:index+1])
    return split_words
print(split_s("life-is-short-you-need-python", '-'))
print(split_s("life-is-short-you-need-python", '-', 2))

Problem 16: Da‑Yan Sequence – Generates the first 100 terms of a sequence where even indices use i²/2 and odd indices use (i²‑1)/2.

for x in range(1,101):
    if x % 2 == 0:
        a = int((x**2)/2)
    else:
        a = int((x**2 - 1)/2)
    print(a)

Problem 17: Most Frequent Letter – Counts character frequencies in a string and outputs the most common lowercase letter and its count.

def analyse_words(words):
    word_dict = {}
    for i in words:
        if i in word_dict:
            word_dict[i] += 1
        else:
            word_dict[i] = 1
    max_key = max(word_dict, key=word_dict.get)
    print(max_key)
    print(word_dict[max_key])
analyse_words('helloworld')

Problem 18: Print Diamond Using a Stack – Uses a stack to store the upper half of a diamond shape and then prints the lower half.

def diamond(n):
    stack = []
    for i in range(1, 2*n):
        if i <= n:
            p_str = ' '*(n-i) + '*'*(2*i-1)
            if i != n:
                stack.append(p_str)
            print(p_str)
        else:
            print(stack.pop())
diamond(5)

Problem 19: Understanding Recursion – Simple recursive function that prints messages before and after the recursive call.

def p(n):
    if n == 0:
        return
    print('递归前->', n)
    p(n-1)
    print('递归后->', n)
p(5)

Problem 20: Fibonacci Recursive Function – Classic recursive implementation returning the nth Fibonacci number.

def fib(n):
    if n <= 2:
        return 1
    return fib(n-1) + fib(n-2)
print(fib(10))  # 55

Problem 21: Maximum of Three Numbers – Determines the largest of three integers using conditional statements.

a, b, c = 10, 6, 18
if a > b:
    max_num = a
else:
    max_num = b
if max_num < c:
    max_num = c
print(max_num)  # 18

Problem 22: Perfect Numbers Under 1000 – Finds numbers equal to the sum of their proper divisors.

def factor_sum(n):
    s_sum = 0
    for i in range(1, n):
        if n % i == 0:
            s_sum += i
    return s_sum
for j in range(1, 1000):
    if j == factor_sum(j):
        print(j)  # 6, 28, 496

Problem 23: Sum of Factorials up to 10! – Computes 1!+2!+...+10! using recursion.

def factor(n):
    if n < 2:
        return 1
    return n * factor(n-1)
s_sum = 0
for i in range(1, 11):
    s_sum += factor(i)
print(s_sum)  # 4037913

Problem 24: Valid Parentheses – Two solutions: (1) repeatedly replace matching pairs until none remain; (2) use a stack to ensure correct ordering.

def valid_str(string):
    if len(string) % 2 == 1:
        return False
    while '()' in string or '[]' in string or '{}' in string:
        string = string.replace('()', '').replace('[]', '').replace('{}', '')
    return string == ''
print(valid_str('()'))
print(valid_str('()[]{}'))
def valid_str(string):
    if len(string) % 2 == 1:
        return False
    stack = []
    pairs = {')':'(', '}':'{', ']':'['}
    for ch in string:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack
print(valid_str('(){}[({[]})]'))

Problem 25: Palindrome Numbers – Two methods: (1) compare a string with its reverse; (2) reverse half of the number and compare.

def is_palindrome(x):
    if x < 0 or (x != 0 and x % 10 == 0):
        return False
    s = str(x)
    return s == s[::-1]
print(is_palindrome(121))  # True
def is_palindrome(x):
    if x < 0 or (x != 0 and x % 10 == 0):
        return False
    reverted = 0
    while x > reverted:
        reverted = reverted * 10 + x % 10
        x //= 10
    return x == reverted or x == reverted // 10
print(is_palindrome(1221))  # True
pythonAlgorithmsFundamentalsProgramming Exercises
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login 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.