3. Not-an-exam 1: Solutions#
1. Circle and annotate/correct any mistakes you find in the code below:
Side-by-side of the mistake-ridden code and correct syntax.

2. The function final_final takes as input a list.
If the list has an odd number of elements, the same list is returned with the final item lopped off.
If the list has an even number of elements, the last two elements are moved to the front of the list.
def final_final(my_list):
L = len(my_list)
if L%2==1:
return my_list[:-1]
else:
return my_list[-2:] + my_list[:-2]
a = final_final([1, 2, 3, 4, 5])
b = final_final(['A', 'B', 'C', 'D'])
c = final_final('h...helloo')
print(f'a = "{a}"')
print(f'b = "{b}"')
print(f'c = "{c}"')
a = "[1, 2, 3, 4]"
b = "['C', 'D', 'A', 'B']"
c = "ooh...hell"
3. The function mystery_fun takes as input a string (letters) and an integer (shift). Any lower-case letter in the string is replaced by the letter shift positions away in the alphabet.
def mystery_fun(letters, shift = 1):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
new_letters = ''
for letter in letters:
if letter in alphabet:
idx = (alphabet.index(letter) + shift) % 26
letter = alphabet[idx]
new_letters += letter
return new_letters
a = mystery_fun('hello')
b = mystery_fun('Hello!?')
c = mystery_fun('OK bye!', shift = 2)
print(f'a = "{a}"')
print(f'b = "{b}"')
print(f'c = "{c}"')
a = "ifmmp"
b = "Hfmmp!?"
c = "OK dag!"
4.
def repeat_by_word(word_list, repeat_list):
repeated_words = ''
for word, repeat in zip(word_list, repeat_list):
repeated_words += (word + ' ') * repeat
repeated_words = repeated_words[:-1] + '!'
return repeated_words
words = ['not', 'true', 'is', 'not', 'the', 'same', 'as', 'false']
repeats = [3, 1, 1, 0, 1, 2, 1, 1]
print(repeat_by_word(words, repeats))
not not not true is the same same as false!
5.
def clip(numlist, upper, lower):
if upper < lower:
lower, upper = upper, lower
new_list = []
for num in numlist:
if num < lower:
new_list.append(lower)
elif num > upper:
new_list.append(upper)
else:
new_list.append(num)
return new_list
data = [5, 9 , 2, 6, 11, 20, -4, 17, 1, 19, 12]
data_clipped = clip(data, 15, 5)
print(data_clipped)
[5, 9, 5, 6, 11, 15, 5, 15, 5, 15, 12]