Practical Coding in Python

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 2025)

Previous: Binimate

Coding Exercises: Loops and Algorithms

Implement the following functions, including unit tests. A few example tests are shown. Add at least 2 more tests of your own for each function.

Sum of Squares

sum_of_squares(1) -> 1
sum_of_squares(2) -> 1+4 = 5
sum_of_squares(3) -> 1+4+9 = 14

Count Occurences

count_occurrences("Mississippi", "iss") -> 2
count_occurrences("banananana", "na") -> 4

Reverse String

reverse("bad") -> "dab"
reverse("Hello, world!") -> "!dlrow ,olleH"
reverse("tacocat") -> "tacocat"

Factorial

factorial(0) -> 1
factorial(1) -> 1
factorial(2) -> 2*1 = 2
factorial(3) -> 3*2*1 = 6
factorial(4) -> 4*3*2*1 = 24
factorial(5) -> 5*4*3*2*1 = 120

Interlace Two Strings

interlace("abc", "123") -> "a1b2c3"
interlace("bed", "ras") -> "breads"

Find 2nd β€œa”

find_2nd("banana") -> 3
find_2nd("happy birthday") -> 12

Add β€œna” suffix

add_na(0) -> "ba"
add_na(1) -> "bana"
add_na(2) -> "banana"
add_na(3) -> "bananana"

Calculate Sum of Powers of 2

sum_powers(0) -> 0
sum_powers(1) -> 0+1 = 1
sum_powers(2) -> 0+1+2 = 3
sum_powers(3) -> 0+1+2+4 = 7
sum_powers(4) -> 0+1+2+4+8 = 15 

Next: