Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Python Programming Exercises with Code Solutions

Notes Apr 25 8

Exercise 001: Number Combinations

Problem: Given four digits: 1, 2, 3, 4, how many unique three-digit numbers can be formed without repetition? List them.

Analysis: Iterate through all possibilities and eliminate duplicates.

Simplified Approach: Use permutations from itertools.

import itertools
count = 0
digits = [1, 2, 3, 4]
for permutation in itertools.permutations(digits, 3):
    print(permutation)
    count += 1
print(count)

Exercise 002: Income Tax Calculation

Problem: A company awards bonuses based on profit tiers. Calculate the total bonus for a given profit input.

Analysis: Compute bonus by tier thresholds.

profit = int(input('Enter profit amount: '))
bonus_total = 0
thresholds = [100000, 100000, 200000, 200000, 400000]
rates = [0.1, 0.075, 0.05, 0.03, 0.015, 0.01]
for index in range(len(thresholds)):
    if profit <= thresholds[index]:
        bonus_total += profit * rates[index]
        profit = 0
        break
    else:
        bonus_total += thresholds[index] * rates[index]
        profit -= thresholds[index]
bonus_total += profit * rates[-1]
print(bonus_total)

Exercise 003: Perfect Square Number

Problem: Find an integer such that adding 100 gives a perfect square, and adding 168 gives another perfect square.

Analysis: Use a brute-force approach within a calculated limit.

limit = 0
while (limit + 1) ** 2 - limit ** 2 <= 168:
    limit += 1

for value in range((limit + 1) ** 2):
    if value ** 0.5 == int(value ** 0.5) and (value + 168) ** 0.5 == int((value + 168) ** 0.5):
        print(value - 100)

Exercise 004: Day of the Year

Problem: Input a date and determine its day number in the year, accounting for leap years.

Analysis: Adjust for February in leap years.

def is_leap_year(year):
    return (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)

days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
total_days = 0
year_input = int(input('Year: '))
month_input = int(input('Month: '))
day_input = int(input('Day: '))
if is_leap_year(year_input):
    days_in_month[2] += 1
for month_index in range(month_input):
    total_days += days_in_month[month_index]
print(total_days + day_input)

Exercise 005: Sorting Three Numbers

Problem: Input three integers and output them in ascending order.

Analysis: Implement a simple sort or use built-in functions.

numbers = []
for i in range(3):
    num = int(input(f'Enter integer {i+1}: '))
    numbers.append(num)

for i in range(len(numbers)):
    for j in range(i, len(numbers)):
        if numbers[i] > numbers[j]:
            numbers[i], numbers[j] = numbers[j], numbers[i]
print(numbers)

# Alternative using sorted
numbers2 = []
for i in range(3):
    num = int(input(f'Enter integer {i+1}: '))
    numbers2.append(num)
print(sorted(numbers2))

Exercise 006: Fibonacci Sequence

Problem: Generate the Fibonacci sequence.

Analysis: Use recursion or iteration.

# Recursive approach
def fibonacci_recursive(n):
    return 1 if n <= 2 else fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
print(fibonacci_recursive(int(input())))

# Iterative approach
term = int(input())
a, b = 1, 1
for _ in range(term - 1):
    a, b = b, a + b
print(a)

Exercise 007: Copying Lists

Problem: Copy data from one list to another, demonstrating shallow and deep copy.

Analysis: Use slicing and copy module.

import copy
original_list = [1, 2, 3, 4, ['a', 'b']]

assignment = original_list  # Reference
slice_copy = original_list[:]  # Shallow copy
shallow_copy = copy.copy(original_list)  # Shallow copy
deep_copy = copy.deepcopy(original_list)  # Deep copy

original_list.append(5)
original_list[4].append('c')

print('Original:', original_list)
print('Assignment:', assignment)
print('Slice Copy:', slice_copy)
print('Shallow Copy:', shallow_copy)
print('Deep Copy:', deep_copy)

Exercise 008: Multiplication Table

Problem: Print a 9x9 multiplication table.

Analysis: Use nested loops for rows and columns.

for row in range(1, 10):
    for col in range(1, row + 1):
        print(f'{row}*{col}={row*col:2d}', end=' ')
    print()

Exercise 009: Pause Output

Problem: Pause output for one second.

Analysis: Use time.sleep().

import time
for iteration in range(4):
    print(str(int(time.time()))[-2:])
    time.sleep(1)

Exercise 010: Formatted Time Output

Problem: Pause and output current time in a formatted way.

Analysis: Similar to Exercise 009 with time formatting.

import time
for iteration in range(4):
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    time.sleep(1)

Exercise 011: Rabbit Breeding

Problem: Model rabbit population growth over months with maturity at three months.

Analysis: Track age groups monthly.

months = int(input('Enter number of months: '))
one_month = 1
two_month = 0
three_month = 0
adult = 0
for month in range(months):
    one_month, two_month, three_month, adult = adult + three_month, one_month, two_month, adult + three_month
    print(f'Month {month+1}: Total rabbits = {one_month + two_month + three_month + adult}')
    print(f'  1-month old: {one_month}')
    print(f'  2-month old: {two_month}')
    print(f'  3-month old: {three_month}')
    print(f'  Adult: {adult}')

Exercise 012: Prime Numbers in Range

Problem: Find and print all prime numbers between 101 and 200.

Analysis: Check divisibility up to square root.

import math
for number in range(100, 201):
    is_prime = True
    for divisor in range(2, int(math.sqrt(number)) + 1):
        if number % divisor == 0:
            is_prime = False
            break
    if is_prime:
        print(number)

# Using else with for loop
for number in range(100, 201):
    for divisor in range(2, int(math.sqrt(number)) + 1):
        if number % divisor == 0:
            break
    else:
        print(number)

Exercise 013: Narcissistic Numbers

Problem: Print all three-digit numbers where the sum of cubes of digits equals the number.

Analysis: Decompose digits and compute.

for num in range(100, 1000):
    digits = str(num)
    if num == int(digits[0])**3 + int(digits[1])**3 + int(digits[2])**3:
        print(num)

Exercise 014: Prime Factorization

Problem: Factorize an integer into prime factors.

Analysis: Iterate from 2 upwards.

target = int(input('Enter an integer: '))
print(f'{target} = ', end='')
if target < 0:
    target = abs(target)
    print('-1*', end='')

if target <= 1:
    print(target)
else:
    factors = []
    divisor = 2
    while target > 1:
        while target % divisor == 0:
            factors.append(str(divisor))
            target //= divisor
        divisor += 1
    print('*'.join(factors))

Exercise 015: Grade Classification

Problem: Classify scores into grades A, B, or C.

Analysis: Use conditional statements.

score = int(input('Enter score: '))
if score >= 90:
    grade = 'A'
elif score < 60:
    grade = 'C'
else:
    grade = 'B'
print(grade)

Exercise 016: Date Formatting

Problem: Output dates in specified formats using datetime module.

Analysis: Utilize datetime functions.

import datetime
print(datetime.date.today())
print(datetime.date(2333, 2, 3))
print(datetime.date.today().strftime('%d/%m/%Y'))
day = datetime.date(1111, 2, 3)
day = day.replace(year=day.year + 22)
print(day)

Exercise 017: Character Statistics

Problem: Count letters, digits, spaces, and other characters in a string.

Analysis: Iterate through characters.

text = input("Enter a string: ")
letter_count = 0
digit_count = 0
space_count = 0
other_count = 0
for char in text:
    if char.isspace():
        space_count += 1
    elif char.isdigit():
        digit_count += 1
    elif char.isalpha():
        letter_count += 1
    else:
        other_count += 1
print(f'Letters: {letter_count}')
print(f'Digits: {digit_count}')
print(f'Spaces: {space_count}')
print(f'Others: {other_count}')

Exercise 018: Repeated Digit Sum

Problem: Compute sum of series like a + aa + aaa + ... for a given digit and count.

Analysis: Use string concatenation.

digit = input('Enter a digit: ')
count = int(input('Enter number of terms: '))
total = 0
current = digit
for _ in range(count):
    total += int(current)
    current += digit[0]
print(f'Result: {total}')

Exercise 019: Perfect Numbers

Problem: Find all perfect numbers up to 1000 (numbers equal to sum of their proper divisors).

Analysis: Collect divisors and sum.

def get_divisors(n):
    divisors = set()
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            divisors.add(i)
            divisors.add(n // i)
    return divisors

for num in range(2, 1001):
    if sum(get_divisors(num)) - num == num:
        print(num)

Exercise 020: Ball Bounce Distance

Problem: Calculate total distance traveled by a ball dropped from 100m, bouncing half height each time, after 10 bounces.

Analysis: Sum distances for each bounce.

height = 100.0
total_distance = 100.0
for bounce in range(10):
    height /= 2
    total_distance += height * 2  # Up and down
print(f'Total distance: {total_distance}')
print(f'Height after 10th bounce: {height}')

Exercise 021: Monkey and Peaches

Problem: Determine initial number of peaches based on daily consumption pattern.

Analysis: Reverse the consumption logic.

peaches = 1
for day in range(9):
    peaches = (peaches + 1) * 2
print(peaches)

Exercise 022: Tournament Matchups

Problem: Assign matchups between two teams with constraints.

Analysis: Use set operations to find valid permutations.

team_a = {'x', 'y', 'z'}
team_b = {'x', 'y', 'z'}
team_c = {'x', 'y', 'z'}
team_c -= {'x', 'z'}
team_a -= {'x'}
for a in team_a:
    for b in team_b:
        for c in team_c:
            if len({a, b, c}) == 3:
                print(f'A: {a}, B: {b}, C: {c}')

Exercise 023: Diamond Pattern

Problem: Print a diamond pattern using asterisks.

Analysis: Use recursive or iterative methods.

def print_diamond(size):
    for i in range(size):
        print(' ' * (size - i - 1) + '*' * (2 * i + 1))
    for i in range(size - 2, -1, -1):
        print(' ' * (size - i - 1) + '*' * (2 * i + 1))

print_diamond(4)

Exercise 024: Fibonacci Fraction Sum

Problem: Sum the first 20 terms of a fraction sequence derived from Fibonacci.

Analysis: Iterate and update numerators and denominators.

numerator = 2.0
denominator = 1.0
sum_series = 0.0
for _ in range(20):
    sum_series += numerator / denominator
    numerator, denominator = numerator + denominator, numerator
print(sum_series)

Exercise 025: Factorial Sum

Problem: Compute sum of factorials from 1! to 20!.

Analysis: Use iterative multiplication.

result = 1
for i in range(20, 1, -1):
    result = i * result + 1
print(result)

Exercise 026: Recursive Factorial

Problem: Calculate factorial using recursion.

Analysis: Define a recursive function.

def factorial_recursive(n):
    return 1 if n <= 1 else n * factorial_recursive(n - 1)
print(factorial_recursive(5))

Exercise 027: Reverse String Recursively

Problem: Print a string in reverse order using recursion.

Analysis: Recursively process substrings.

def reverse_print(s):
    if len(s) == 0:
        return
    reverse_print(s[1:])
    print(s[0], end='')

reverse_print(input('Enter a string: '))

Exercise 028: Recursive Age Calculation

Problem: Find age of fifth person in an arithmetic sequence using recursion.

Analysis: Recursively add differences.

def calculate_age(n):
    return 10 if n == 1 else 2 + calculate_age(n - 1)
print(calculate_age(5))

Exercise 029: Reverse and Count Digits

Problem: For a positive integer, count digits and print in reverse.

Analysis: Convert to string for manipulation.

number = input('Enter a positive integer: ')
print(f'Number of digits: {len(number)}')
print(f'Reversed: {number[::-1]}')

Exercise 030: Palindrome Check

Problem: Check if a 5-digit number is a palindrome.

Analysis: Compare characters from both ends.

text = input('Enter a number or string: ')
is_palindrome = True
left, right = 0, len(text) - 1
while left < right:
    if text[left] != text[right]:
        is_palindrome = False
        break
    left += 1
    right -= 1
print('Palindrome' if is_palindrome else 'Not a palindrome')

Exercise 031: Day of Week from Letter

Problem: Identify day of week based on first letter(s).

Analysis: Use dictionary mapping.

day_map = {
    'm': 'Monday',
    't': {'h': 'Thursday', 'u': 'Tuesday'},
    'w': 'Wednesday',
    'f': 'Friday',
    's': {'a': 'Saturday', 'u': 'Sunday'}
}
first = input('Enter first letter: ').lower()
if first in day_map:
    if isinstance(day_map[first], dict):
        second = input('Enter second letter: ').lower()
        print(day_map[first].get(second, 'Invalid'))
    else:
        print(day_map[first])
else:
    print('Invalid input')

Exercise 032: Reverse List

Problem: Print list values in reverse order.

Analysis: Use slicing.

items = ['one', 'two', 'three']
print(items[::-1])

Exercise 033: List to Comma-Separated String

Problem: Convert list to comma-separated string.

Analysis: Use join with string conversion.

numbers = [1, 2, 3, 4, 5]
print(','.join(map(str, numbers)))

Exercise 034: Function Calls

Problem: Demonstrate function calling.

Analysis: Define and call functions.

def greet():
    print('Hello World!')

def repeat_greet():
    for _ in range(2):
        greet()

if __name__ == '__main__':
    repeat_greet()

Exercise 035: Text Color Setting

Problem: Set text colors using ANSI codes.

Analysis: Define color constants.

class Colors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

print(Colors.WARNING + "Warning text in color" + Colors.ENDC)

Exercise 036: Prime Numbers in Range

Problem: Find primes within a given range.

Analysis: Check divisibility.

lower = int(input('Lower bound: '))
upper = int(input('Upper bound: '))
for num in range(lower, upper + 1):
    if num > 1:
        for div in range(2, int(num**0.5) + 1):
            if num % div == 0:
                break
        else:
            print(num)

Exercise 037: Sort Ten Numbers

Problem: Sort ten input numbers.

Analysis: Implement bubble sort or use sorted.

values = []
for i in range(10):
    val = int(input(f'Enter number {i+1}: '))
    values.append(val)

for i in range(len(values)):
    for j in range(i, len(values)):
        if values[i] > values[j]:
            values[i], values[j] = values[j], values[i]
print(values)

Exercise 038: Matrix Diagonal Sum

Problem: Sum main diagonal elements of a 3x3 matrix.

Analysis: Access diagonal indices.

matrix = [[1, 2, 3],
          [3, 4, 5],
          [4, 5, 6]]
diagonal_sum = 0
for idx in range(len(matrix)):
    diagonal_sum += matrix[idx][idx]
print(diagonal_sum)

Exercise 039: Insert into Sorted List

Problem: Insert a number into a sorted list while maintaining order.

Analysis: Find position and shift elements.

sorted_list = [1, 10, 100, 1000, 10000, 100000]
new_num = int(input('Enter a number to insert: '))
sorted_list.append(new_num)
for i in range(len(sorted_list) - 1):
    if sorted_list[i] >= new_num:
        for j in range(i, len(sorted_list)):
            sorted_list[j], sorted_list[-1] = sorted_list[-1], sorted_list[j]
        break
print(sorted_list)

Exercise 040: Reverse List

Problem: Reverse a list in place.

Analysis: Swap elements or use reverse method.

data = [1, 10, 100, 1000, 10000, 100000]
for i in range(len(data) // 2):
    data[i], data[-i-1] = data[-i-1], data[i]
print('Method 1:', data)

data2 = [1, 10, 100, 1000, 10000, 100000]
data2.reverse()
print('Method 2:', data2)

Exercise 041: Class Methods and Variables

Problem: Demonstrate class vs instance variables.

Analysis: Define a class with static and instance attributes.

class Counter:
    static_count = 0  # Class variable
    def __init__(self):
        self.instance_count = 0  # Instance variable
    def increment(self):
        self.instance_count += 1
        Counter.static_count += 1
        print(f'Instance: {self.instance_count}, Static: {Counter.static_count}')

obj = Counter()
for _ in range(5):
    obj.increment()

Exercise 042: Variable Scope

Problem: Illustrate local and global variable scope.

Analysis: Use global keyword.

global_var = 0

def local_example():
    local_var = 0
    print(local_var)
    local_var += 1

def global_example():
    global global_var
    print(global_var)
    global_var += 1

for _ in range(3):
    local_example()
    global_example()

Exercise 043: Static Variable Example

Problem: Another example of static variables in classes.

Analysis: Combine class and instance variables.

class Example:
    class_var = 0
    def __init__(self):
        self.instance_var = 0
    def update(self):
        self.instance_var += 1
        Example.class_var += 1
        print(f'Instance: {self.instance_var}, Class: {Example.class_var}')

obj1 = Example()
obj2 = Example()
for _ in range(3):
    obj1.update()
    obj2.update()

Exercise 044: Matrix Addition

Problem: Add two matrices.

Analysis: Iterate through rows and columns.

matrix_a = [[12, 7, 3],
            [4, 5, 6],
            [7, 8, 9]]
matrix_b = [[5, 8, 1],
            [6, 7, 3],
            [4, 5, 9]]
result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]
for row in range(len(matrix_a)):
    for col in range(len(matrix_a[0])):
        result[row][col] = matrix_a[row][col] + matrix_b[row][col]
print(result)

Exercise 045: Sum from 1 to 100

Problem: Compute sum of integers from 1 to 100.

Analysis: Use loop or formula.

total = 0
for i in range(1, 101):
    total += i
print(total)

Exercise 046: Exit on Condition

Problem: Square input numbers and exit if square is less than 50.

Analysis: Use while loop with break.

while True:
    try:
        num = float(input('Enter a number: '))
    except ValueError:
        print('Invalid input, try again.')
        continue
    square = num ** 2
    print(f'Square: {square}')
    if square < 50:
        print('Square less than 50, exiting.')
        break

Exercise 047: Swap Variables with Function

Problem: Swap two variable values using a function.

Analysis: Return tuple for swapping.

def swap_values(x, y):
    return y, x

a = 0
b = 10
a, b = swap_values(a, b)
print(a, b)

Exercise 048: Compare Numbers

Problem: Compare two numbers and print relation.

Analysis: Use conditional statements.

first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
if first < second:
    print(f'{first} < {second}')
elif first > second:
    print(f'{first} > {second}')
else:
    print(f'{first} = {second}')

Exercise 049: Lambda Functions

Problem: Create anonymous functions for max and min.

Analysis: Use lambda expressions.

maximum = lambda x, y: x if x >= y else y
minimum = lambda x, y: x if x <= y else y

num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print(f'Max: {maximum(num1, num2)}')
print(f'Min: {minimum(num1, num2)}')

Exercise 050: Random Number

Problem: Generate a random number within a range.

Analysis: Use random module.

import random
print(random.uniform(10, 20))

Exercise 051: Bitwise AND

Problem: Demonstrate bitwise AND operation.

Analysis: Perform AND on octal numbers.

a = 0o77
print(a)
b = a & 3
print(b)
b = b & 7
print(b)

Exercise 052: Bitwise OR

Problem: Demonstrate bitwise OR operation.

Analysis: Perform OR on octal numbers.

a = 0o77
print(a | 3)
print(a | 3 | 7)

Exercise 053: Bitwise XOR

Problem: Demonstrate bitwise XOR operation.

Analysis: Perform XOR on octal numbers.

a = 0o77
print(a ^ 3)
print(a ^ 3 ^ 7)

Exercise 054: Extract Bits

Problem: Extract specific bits from an integer.

Analysis: Use bit shifting and masking.

value = int(input('Enter a number: '))
mask = ~(~0 << 4)  # Mask for lower 4 bits
extracted = (value >> 4) & mask
print(f'Original: {bin(value)}')
print(f'Extracted bits (4-7): {bin(extracted)}')

Exercise 055: Bitwise NOT

Problem: Demonstrate bitwise NOT operation.

Analysis: Apply NOT to integers.

print(~234)
print(~~234)

Exercise 056: Draw Circle with Tkinter

Problem: Draw concentric circles using Tkinter.

Analysis: Use Canvas oval creation.

from tkinter import *
canvas = Canvas(width=800, height=600, bg='yellow')
canvas.pack(expand=YES, fill=BOTH)
radius = 1
growth = 1
for _ in range(26):
    canvas.create_oval(310 - radius, 250 - radius, 310 + radius, 250 + radius, width=1)
    radius += growth
growth += 0.3
mainloop()

Exercise 057: Draw Lines with Tkinter

Problem: Draw lines in a pattern using Tkinter.

Analysis: Use Canvas line creation.

from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x_start, y_start = 263, 263
for i in range(19):
    canvas.create_line(x_start, y_start, x_start, y_start + 12, width=1, fill='red')
    x_start -= 5
    y_start -= 5
mainloop()

Exercise 058: Draw Rectangle with Tkinter

Problem: Draw rectangles using Tkinter.

Analysis: Use Canvas rectangle creation.

from tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root, width=400, height=400, bg='yellow')
x0, y0 = 263, 263
x1, y1 = 275, 275
for _ in range(19):
    canvas.create_rectangle(x0, y0, x1, y1)
    x0 -= 5
    y0 -= 5
    x1 += 5
    y1 += 5
canvas.pack()
root.mainloop()

Exercise 059: Complex Drawing with Tkinter

Problem: Draw a complex pattern using Tkinter.

Analysis: Combine circles and lines.

from tkinter import *
import math
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
center_x, center_y = 150, 100
for radius in [10, 20, 50]:
    canvas.create_oval(center_x - radius, center_y - radius, center_x + radius, center_y + radius)
for angle in range(0, 360, 22.5):
    rad = math.radians(angle)
    x = center_x + 48 * math.cos(rad)
    y = center_y + 48 * math.sin(rad) * 0.809
    canvas.create_line(center_x, center_y, x, y, fill='red')
mainloop()

Exercise 060: String Length

Problem: Compute length of a string.

Analysis: Use len() function.

text = 'example_string'
print(len(text))

Exercise 061: Pascal's Triangle

Problem: Print first 10 rows of Pascal's triangle.

Analysis: Generate rows iteratively.

def pascals_triangle(rows):
    triangle = [[1]]
    for i in range(1, rows):
        prev_row = triangle[-1]
        new_row = [1] + [prev_row[j] + prev_row[j+1] for j in range(len(prev_row)-1)] + [1]
        triangle.append(new_row)
    return triangle

for row in pascals_triangle(10):
    print(row)

Exercise 062: Find Substring

Problem: Find positions of substrings in a string.

Analysis: Use find() method.

main_string = 'aabbxuebixuebi'
sub1 = 'ab'
sub2 = 'xue'
print(main_string.find(sub1))
print(main_string.find(sub2))

Exercise 063: Draw Ellipse with Tkinter

Problem: Draw ellipses using Tkinter.

Analysis: Use Canvas oval with varying dimensions.

from tkinter import *
canvas = Canvas(width=400, height=600, bg='white')
x_center, y_center = 250, 250
top_radius = 30
bottom_radius = 30
for _ in range(20):
    canvas.create_oval(x_center - top_radius, y_center - bottom_radius,
                       x_center + top_radius, y_center + bottom_radius)
    top_radius -= 5
    bottom_radius += 5
canvas.pack()
mainloop()

Exercise 064: Draw Ellipse and Rectangle

Problem: Draw combined shapes with Tkinter.

Analysis: Create ovals and rectangles.

from tkinter import *
canvas = Canvas(width=400, height=600, bg='white')
left, right, top = 20, 50, 50
for i in range(15):
    canvas.create_oval(250 - right, 250 - left, 250 + right, 250 + left)
    canvas.create_oval(250 - 20, 250 - top, 250 + 20, 250 + top)
    canvas.create_rectangle(20 - 2*i, 20 - 2*i, 10*(i+2), 10*(i+2))
    right += 5
    left += 5
    top += 10
canvas.pack()
mainloop()

Exercise 065: Draw Pattern with Tkinter

Problem: Draw an aesthetic pattern using Tkinter.

Analysis: Use mathematical functions for coordinates.

from tkinter import *
import math
canvas = Canvas(width=400, height=400, bg='white')
points = []
center_x, center_y = 200, 200
radius = 150
for angle in range(0, 360, 24):
    rad = math.radians(angle)
    x = center_x + radius * math.cos(rad)
    y = center_y + radius * math.sin(rad)
    points.append((x, y))
for i in range(len(points)):
    for j in range(i, len(points)):
        canvas.create_line(points[i][0], points[i][1], points[j][0], points[j][1])
canvas.pack()
mainloop()

Exercise 066: Sort Three Numbers

Problem: Sort three input numbers (similar to Exercise 005).

Analysis: Use sorting algorithm.

numbers = []
for i in range(3):
    num = int(input(f'Enter number {i+1}: '))
    numbers.append(num)
numbers.sort()
print(numbers)

Exercise 067: Swap Max and Min in List

Problem: Swap max with first element and min with last in a list.

Analysis: Find indices and swap.

data = [3, 2, 5, 7, 8, 1, 5]
max_idx = data.index(max(data))
data[0], data[max_idx] = data[max_idx], data[0]
min_idx = data.index(min(data))
data[-1], data[min_idx] = data[min_idx], data[-1]
print(data)

Exercise 068: Rotate List

Problem: Rotate list elements by m positions.

Aanlysis: Use deque for rotation.

from collections import deque
original = [1, 2, 3, 4, 5, 6, 7, 8, 9]
rotate_by = int(input('Enter rotation count: '))
deq = deque(original, maxlen=len(original))
deq.rotate(rotate_by)
print(list(deq))

Exercise 069: Josephus Problem

Problem: Simulate elimination in a circle to find last remaining person.

Analysis: Use list to track active members.

total = int(input('Enter total number of people: '))
people = list(range(1, total + 1))
index = 0
count = 0
while len(people) > 1:
    count += 1
    if count == 3:
        people.pop(index)
        count = 0
    else:
        index = (index + 1) % len(people)
print(f'Last remaining: {people[0]}')

Exercise 070: String Length Function

Problem: Write a function to return string length.

Analysis: Define function using len().

def string_length(s):
    return len(s)

print(string_length('test_string'))

Exercise 071: Input and Output Functions

Problem: Define functions to input and output student records.

Analysis: Use lists to store data.

def input_students():
    students = []
    for i in range(3):
        num = input(f'Enter student {i+1} number: ')
        name = input(f'Enter student {i+1} name: ')
        scores = []
        for j in range(3):
            score = int(input(f'Enter score {j+1}: '))
            scores.append(score)
        students.append([num, name, scores])
    return students

def output_students(students):
    for student in students:
        print(f'Number: {student[0]}, Name: {student[1]}')
        print(f'Scores: {student[2]}')

if __name__ == '__main__':
    data = input_students()
    output_students(data)

Exercise 072: Linked List Implementation

Problem: Implement a basic linked list.

Analysis: Define Node and List classes.

class ListNode:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    def append(self, value):
        new_node = ListNode(value)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node
    def display(self):
        elements = []
        current = self.head
        while current:
            elements.append(current.value)
            current = current.next
        print(elements)

ll = LinkedList()
for i in range(10):
    ll.append(i)
ll.display()

Exercise 073: Reverse Linked List Output

Problem: Output linked list in reverse order.

Analysis: Traverse and collect values, then reverse.

class ListNode:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    def append(self, value):
        new_node = ListNode(value)
        if not self.head:
            self.head = new_node
            return
        current = self.head
        while current.next:
            current = current.next
        current.next = new_node
    def reverse_display(self):
        values = []
        current = self.head
        while current:
            values.append(current.value)
            current = current.next
        print(values[::-1])

ll = LinkedList()
for i in range(10):
    ll.append(i)
ll.reverse_display()

Exercise 074: List Sorting and Concatenation

Problem: Sort and concatenate two lists.

Analysis: Use sort() and extend().

list_a = [2, 6, 8]
list_b = [7, 0, 4]
list_a.extend(list_b)
list_a.sort()
print(list_a)

Exercise 075: Simple Logic Puzzle

Problem: Solve a simple conditional puzzle.

Analysis: Evaluate conditions for each number.

for i in range(5):
    conditions_met = 0
    if i != 1:
        conditions_met += 1
    if i == 3:
        conditions_met += 1
    if i == 4:
        conditions_met += 1
    if i != 4:
        conditions_met += 1
    if conditions_met == 3:
        print(64 + i)

Exercise 076: Series Sum Function

Problem: Define function to sum series based on parity of n.

Analysis: Use separate functions for even and odd.

def sum_even_series(n):
    total = 0.0
    for i in range(2, n + 1, 2):
        total += 1.0 / i
    return total

def sum_odd_series(n):
    total = 0.0
    for i in range(1, n + 1, 2):
        total += 1.0 / i
    return total

def calculate_series(n):
    if n % 2 == 0:
        return sum_even_series(n)
    else:
        return sum_odd_series(n)

n_value = int(input('Enter a number: '))
print(calculate_series(n_value))

Exercise 077: Iterate Through List

Problem: Loop through and print list items.

Analysis: Use for loop.

items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
for item in items:
    print(item)

Exercise 078: Find Oldest Person in Dictionary

Problem: Find person with maximum age in a dictionary.

Analysis: Iterate through dictionary items.

ages = {"Alice": 18, "Bob": 50, "Charlie": 20, "Diana": 22}
oldest = max(ages, key=ages.get)
print(f'{oldest}, {ages[oldest]}')

Exercise 079: Sort Strings

Problem: Sort a list of strings.

Analysis: Use sort() method.

strings = ['baaa', 'aaab', 'aaba', 'aaaa', 'abaa']
strings.sort()
print(strings)

Exercise 080: Monkey and Peach Problem

Problem: Find minimum initial peaches based on division pattern.

Analysis: Solve equation iteratively.

peaches = 1
for _ in range(5):
    peaches = peaches * 5 + 1
print(peaches)

Exercise 081: Solve Equation

Problem: Find two-digit number satisfying given equation.

Analysis: Brute-force check.

for num in range(10, 100):
    if 809 * num == 800 * num + 9 * num and 1000 <= 809 * num < 10000 and 10 <= 8 * num < 100 and 100 <= 9 * num < 1000:
        print(f'Number: {num}, Result: {809 * num}')
        break

Exercise 082: Octal to Decimal Conversion

Problem: Convert octal number to decimal.

Analysis: Use int() with base 8.

octal_input = input('Enter octal number: ')
decimal_value = int(octal_input, 8)
print(decimal_value)

Exercise 083: Count Odd Numbers Formed

Problem: Count odd numbers that can be formed with digits 0-7.

Analysis: Calculate based on digit positions.

total = 4  # 1-digit odds
multiplier = 7
for digits in range(2, 9):
    if digits <= 2:
        total += multiplier * 4
    else:
        multiplier *= 8
        total += multiplier * 4
print(f'Total odd numbers: {total}')

Exercise 084: Join Strings with Delimiter

Problem: Join list of strings with a comma.

Analysis: Use join() method.

countries = ['Brazil', 'Russia', 'India', 'China']
print(','.join(countries))

Exercise 085: Divisibility by 9s

Problem: Find how many 9's are needed to be divisible by an odd number.

Analysis: Incrementally form numbers with 9's.

def find_nines(divisor):
    number = 9
    count = 1
    while number % divisor != 0:
        number = number * 10 + 9
        count += 1
    return count, number

divisor = int(input('Enter an odd number: '))
count, result = find_nines(divisor)
print(f'{count} nines form {result}, divisible by {divisor}')

Exercise 086: Concatenate Strings

Problem: Concatenate two strings.

Analysis: Use + operator.

str1 = 'hello'
str2 = 'world'
print(str1 + str2)

Exercise 087: Modify Class Attributes

Problem: Demonstrate passing class instances to functions.

Analysis: Define class and function that modifies attributes.

class Sample:
    def __init__(self):
        self.value = 0
        self.char = ''

def modify(obj):
    obj.value = 20
    obj.char = 'c'

obj = Sample()
obj.value = 3
obj.char = 'a'
modify(obj)
print(obj.value, obj.char)

Exercise 088: Print Asterisks Based on Input

Problem: Print asterisks equal to input numbers.

Analysis: Use multiplication for string repetition.

for _ in range(3):
    num = int(input('Enter a number between 1 and 50: '))
    print('*' * num)

Exercise 089: Simple Encryption

Problem: Encrypt a 4-digit number by adding 5, taking remainder, and swapping digits.

Analsyis: Process each digit.

def encrypt(number):
    digits = [int(d) for d in str(number)]
    encrypted = [(d + 5) % 10 for d in digits]
    encrypted[0], encrypted[3] = encrypted[3], encrypted[0]
    encrypted[1], encrypted[2] = encrypted[2], encrypted[1]
    return ''.join(map(str, encrypted))

num = input('Enter a 4-digit number: ')
print(encrypt(num))

Exercise 090: List Operations Examples

Problem: Demonstrate various list operations.

Analysis: Show methods like append, pop, slicing.

example_list = [10086, 'example', [1, 2, 4, 5]]
print(len(example_list))
print(example_list[1:])
example_list.append('new item')
print(example_list[-1])
print(example_list.pop(1))
print(example_list)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([row[1] for row in matrix])
print([row[1] for row in matrix if row[1] % 2 == 0])

Exercise 091: Time Module Basics

Problem: Display current time in different formats.

Analysis: Use time module functions.

import time
print(time.ctime())
print(time.asctime(time.localtime()))
print(time.asctime(time.gmtime()))

Exercise 092: Measure Execution Time

Problem: Measure time taken to print numbers.

Analysis: Use time.time() for timing.

import time
start = time.time()
for i in range(3000):
    print(i, end=' ')
end = time.time()
print(f'\nTime elapsed: {end - start} seconds')

Exercise 093: Time with clock()

Problem: Use time.clock() for precision timing (deprecated in Python 3.8).

Analysis: Alternative using time.perf_counter().

import time
start = time.perf_counter()
for i in range(100):
    print(i, end=' ')
end = time.perf_counter()
print(f'\nTime: {end - start:.3f} seconds')

Exercise 094: Guessing Game with Timing

Problem: Implement a number guessing game with time measurement.

Analysis: Use random and time modules.

import time
import random
number = random.randint(1, 100)
start = time.time()
guess = int(input('Guess the number (1-100): '))
while guess != number:
    if guess > number:
        print('Too high')
    else:
        print('Too low')
    guess = int(input('Try again: '))
end = time.time()
print(f'Correct! Time taken: {end - start:.2f} seconds')

Exercise 095: Parse Date String

Problem: Convert string date to datetime object.

Analysis: Use dateutil.parser or datetime.strptime.

from datetime import datetime
date_str = "Aug 28 2015 12:00AM"
date_obj = datetime.strptime(date_str, "%b %d %Y %I:%M%p")
print(date_obj)

Exercise 096: Count Substring Occurrences

Problem: Count how many times a substring appears in a string.

Analysis: Use count() method.

main = 'xuebixuebixuebixuebixuebixuebixuebixue'
sub = 'xuebi'
print(main.count(sub))

Exercise 097: Write to File Until Sentinel

Problem: Write characters to a file until '#' is entered.

Analysis: Use file writing in a loop.

filename = input('Enter filename: ')
with open(filename, 'w') as file:
    while True:
        char = input('Enter character (or # to stop): ')
        if char == '#':
            break
        file.write(char)
print('File written.')

Exercise 098: Convert to Uppercase and Write to File

Problem: Convert input string to uppercase and save to file.

Analysis: Use string.upper() and file writing.

text = input('Enter a string: ').upper()
with open('output.txt', 'w') as file:
    file.write(text)
print('Uppercase text written to output.txt')

Exercise 099: Merge and Sort Files

Problem: Merge two files, sort content, and write to a new file.

Analysis: Read files, combine, sort, and write.

with open('file_a.txt', 'r') as f1, open('file_b.txt', 'r') as f2:
    content = f1.read() + f2.read()
sorted_content = ''.join(sorted(content))
with open('file_c.txt', 'w') as f3:
    f3.write(sorted_content)
print('Files merged and sorted into file_c.txt')

Exercise 100: Convert List to Dictionary

Problem: Convert two lists into a dictionary using zip.

Analysis: Use dict() with zip().

keys = ['a', 'b']
values = [1, 2]
result = dict(zip(keys, values))
print(result)

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Spring Boot MyBatis with Two MySQL DataSources Using Druid

Required dependencies application.properties: define two data sources and poooling Java configuration for both data sources MyBatis mappers for each data source Controller endpoints to verify both co...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.