You are on page 1of 14

Python challenges and their solutions

Aliou Diouf

aliou.diouf5@gmail.com

www.mathgame-py.com

February 28, 2023

1
Summary
1 Capital indexes 4
1.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Middle letter 4
2.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Online status 5
3.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

4 Randomness 5
4.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

5 Type check 6
5.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

6 Double letters 6
6.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

7 Adding and removing dots 7


7.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

8 Counting syllables 7
8.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
8.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

9 Anagrams 8
9.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
9.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

10 8
10.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
10.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

11 Min-maxing 9
11.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
11.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2
12 Divisible by 3 9
12.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
12.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

13 Tic tac toe input 9


13.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
13.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

14 Palindrome 10
14.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
14.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

15 Up and down 11
15.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
15.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

16 Consecutive zeros 11
16.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
16.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
16.3 Shorter solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

17 All equal 12
17.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
17.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

18 Boolean and 13
18.1 The challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
18.2 My solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
18.3 Other solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3
Introduction
This is a collection of challenges and my solutions.

1 Capital indexes
1.1 The challenge
Write a function named capital indexes. The function takes a single parameter,
which is a string. Your function should return a list of all the indexes in the
string that have capital letters.

For example, calling capital indexes(”HeLlO”) should return the list [0, 2,
4].

1.2 My solution
def capital_indexes(string):
return [i for i, el in enumerate(string) if el.isupper()]

2 Middle letter
2.1 The challenge
Write a function named mid that takes a string as its parameter. Your function
should extract and return the middle letter. If there is no middle letter, your
function should return the empty string.

For example, mid(”abc”) should return ”b” and mid(”aaaa”) should return
””.

2.2 My solution
def mid(string):

n = len(string)
if n % 2 == 0:
return ’’

return string[n//2]

4
3 Online status
3.1 The challenge
The aim of this challenge is, given a dictionary of people’s online status, to
count the number of people who are online.

For example, consider the following dictionary:

statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
}

In this case, the number of people online is 2.

Write a function named online count that takes one parameter. The param-
eter is a dictionary that maps from strings of names to the string ”online” or
”offline”, as seen above.

Your function should return the number of people who are online.

3.2 My solution
def online_count(dct):
ctr = 0
for key, val in dct.items():
if val == ’online’:
ctr += 1
return ctr

4 Randomness
4.1 The challenge
Define a function, random number, that takes no parameters. The function
must generate a random integer between 1 and 100, both inclusive, and return
it.

Calling the function multiple times should (usually) return different num-
bers.

5
For example, calling random number() some times might first return 42,
then 63, then 1.

4.2 My solution
from random import randrange
def random_number():
return randrange(1, 101)

5 Type check
5.1 The challenge
Write a function named only ints that takes two parameters. Your function
should return True if both parameters are integers, and False otherwise.

For example, calling only ints(1, 2) should return True, while calling only ints(”a”,
1) should return False.

5.2 My solution
def only_ints(int1, int2):
return type(int1) == int and type(int2) == int

6 Double letters
6.1 The challenge
The goal of this challenge is to analyze a string to check if it contains two of
the same letter in a row. For example, the string ”hello” has l twice in a row,
while the string ”nono” does not have two identical letters in a row.

Define a function named double letters that takes a single parameter. The
parameter is a string. Your function must return True if there are two identical
letters in a row in the string, and False otherwise.

6.2 My solution
def double_letters(string):
for i, c in enumerate(string[:-1]):
if c == string[i+1]:
return True
return False

6
7 Adding and removing dots
7.1 The challenge
Write a function named add dots that takes a string and adds ”.” in between
each letter. For example, calling add dots(”test”) should return the string
”t.e.s.t”.

Then, below the add dots function, write another function named remove dots
that removes all dots from a string. For example, calling remove dots(”t.e.s.t”)
should return ”test”.

If both functions are correct, calling remove dots(add dots(string)) should


return back the original string for any string.

(You may assume that the input to add dots does not itself contain any
dots.)

7.2 My solution
def add_dots(string):
out = ’’
for char in string[:-1]:
out += char + ’.’
return out + string[-1]

def remove_dots(string):
return string.replace(’.’, ’’)

8 Counting syllables
8.1 The challenge
Define a function named count that takes a single parameter. The parameter is
a string. The string will contain a single word divided into syllables by hyphens,
such as these:

"ho-tel"
"cat"
"met-a-phor"
"ter-min-a-tor"

Your function should count the number of syllables and return it.

7
For example, the call count(”ho-tel”) should return 2.

8.2 My solution
def count(string):
return(len(string.split(’-’)))

9 Anagrams
9.1 The challenge
Two strings are anagrams if you can make one from the other by rearranging
the letters.

Write a function named is anagram that takes two strings as its parameters.
Your function should return True if the strings are anagrams, and False other-
wise.

For example, the call is anagram(”typhoon”, ”opython”) should return True


while the call is anagram(”Alice”, ”Bob”) should return False.

9.2 My solution
def is_anagram(str1, str2):

dict1 = {}
for i, char in enumerate(str1):
dict1[char] = dict1.get(char, 0) + 1

dict2 = {}
for i, char in enumerate(str2):
dict2[char] = dict2.get(char, 0) + 1

return dict1 == dict2

10 Flatten a list
10.1 The challenge
Write a function that takes a list of lists and flattens it into a one-dimensional
list.

8
Name your function flatten. It should take a single parameter and return a
list.

For example, calling:

flatten([[1, 2], [3, 4]])

Should return the list:

[1, 2, 3, 4]

10.2 My solution
def flatten(list_of_lists):
return [item for lst in list_of_lists for item in lst]

11 Min-maxing
11.1 The challenge
Define a function named largest difference that takes a list of numbers as its
only parameter.
Your function should compute and return the difference between the largest
and smallest number in the list.
For example, the call largest difference([1, 2, 3]) should return 2 because 3 -
1 is 2.
You may assume that no numbers are smaller or larger than -100 and 100.

11.2 My solution
def largest_difference(num_list):
return max(num_list) - min(num_list)

12 Divisible by 3
12.1 The challenge
Define a function named div 3 that returns True if its single integer parameter
is divisible by 3 and False otherwise.
For example, div 3(6) is True because 6/3 does not leave any remainder.
However div 3(5) is False because 5/3 leaves 2 as a remainder.

9
12.2 My solution
def div_3(n):
return (n % 3 == 0)

13 Tic tac toe input


13.1 The challenge
Here’s the backstory for this challenge: imagine you’re writing a tic-tac-toe
game, where the board looks like this:

1: X | O | X
-----------
2: | |
-----------
3: O | |

A B C

The board is represented as a 2D list:

board = [
["X", "O", "X"],
[" ", " ", " "],
["O", " ", " "],
]

Imagine if your user enters ”C1” and you need to see if there’s an X or O in
that cell on the board. To do so, you need to translate from the string ”C1” to
row 0 and column 2 so that you can check board[row][column].

Your task is to write a function that can translate from strings of length 2 to
a tuple (row, column). Name your function get row col; it should take a single
parameter which is a string of length 2 consisting of an uppercase letter and a
digit.

For example, calling get row col(”A3”) should return the tuple (2, 0) because
A3 corresponds to the row at index 2 and column at index 0 in the board.

13.2 My solution
def get_row_col(str_len2):
"""Gets row and column"""

10
col = str_len2[0]
row = str_len2[1]

# Checking requirements
if len(str_len2) != 2:
return {’Error’: ’Input parameter is not of length 2’}
if not col.isupper():
return {’Error’: ’The first character is not uppercase letter’}
if not row.isdigit():
return {’Error’: ’The second character is not digit’}

columns = {’A’: 0, ’B’: 1, ’C’: 2}

return (int(row) - 1, columns[col])

14 Palindrome
14.1 The challenge
A string is a palindrome when it is the same when read backwards.

For example, the string ”bob” is a palindrome. So is ”abba”. But the string
”abcd” is not a palindrome, because ”abcd” != ”dcba”.

Write a function named palindrome that takes a single string as its param-
eter. Your function should return True if the string is a palindrome, and False
otherwise.

14.2 My solution
def palindrome(string):
return string[::-1] == string

15 Up and down
15.1 The challenge
Up and down

Define a function named up down that takes a single number as its param-
eter. Your function return a tuple containing two numbers; the first should be
one lower than the parameter, and the second should be one higher.

11
For example, calling up down(5) should return (4, 6).

15.2 My solution
def up_down(n):
return (n-1, n+1)

16 Consecutive zeros
16.1 The challenge
The goal of this challenge is to analyze a binary string consisting of only zeros
and ones. Your code should find the biggest number of consecutive zeros in the
string. For example, given the string:
”1001101000110”

The biggest number of consecutive zeros is 3.

Define a function named consecutive zeros that takes a single parameter,


which is the string of zeros and ones. Your function should return the number
described above.

16.2 My solution
def consecutive_zeros(string):
"""Finds the biggest number of consecutive zeros in string"""

n = 0
counter = 0

for i in string:
if i != ’0’ and i != ’1’:
return {’Error’: ’The string does not match the requirements’}
if i == ’0’:
counter += 1
else:
if counter > n:
n = counter
counter = 0

if counter > n:
n = counter

return n

12
16.3 Shorter solution
This is a shorter solution, but calls three functions: split, len and max. And
there is a cost for each function call, particularly in the loop inside the list
comprehension. A solution may fit well for small data, and not for big data and
vice versa.
def consecutive_zeros(bin_str):
return max([len(s) for s in bin_str.split("1")])

17 All equal
17.1 The challenge
Define a function named all equal that takes a list and checks whether all ele-
ments in the list are the same.

For example, calling all equal([1, 1, 1]) should return True.

17.2 My solution
def all_equal(lst):
"""
Takes a list and checks whether all elements in the list are the same.
"""

for el in lst:
if el != lst[0]:
return False
return True
This solution is not naive, here I do not use nested loop but just one loop.
My solution is algorithmic complexity: O(n) while nested loop solution would
be: O(n2 )

18 Boolean and
18.1 The challenge
Define a function named triple and that takes three parameters and returns
True only if they are all True and False otherwise.

18.2 My solution
def triple_and(bool1, bool2, bool3):
return all((bool1, bool2, bool3))

13
18.3 Other solution
def triple_and(a, b, c):
return a and b and c

14

You might also like