Homework 4 (Main)
Homework 4 (Main)
Homework 4
100 points
Due: Midnight Tuesday March 5 on Moodle.
For programs, hand-in your Python code AND the tests you ran to
verify that the program is working correctly.
1. Write at least three testcases for the following that test the following:
a. an average case
b. an edge case
c. an error case. (10
points)
def find_capitalized_indexes(word):
capitalized_indexes = []
for i in range(len(word)):
if word[i].isupper():
capitalized_indexes.append(i)
return capitalized_indexes
# Function definition
def find_capitalized_indexes(word):
capitalized_indexes = []
for i in range(len(word)):
if word[i].isupper():
capitalized_indexes.append(i)
return capitalized_indexes
# Test cases
# a. Average case
print(find_capitalized_indexes("HelloWorld")) # Expected: [0, 5]
2. Trace the execution of mystery1([2, 4, 1, 3]). Show the trace and the result. Then
determine what the function is computing, for any list. (Don’t explain what the code is
doing – determine what the relationship is between the input list and the returned list. In
other words, what is the purpose of this function. ) Note that the min function returns the
smallest element in a list and the remove function removes the specified element from the
list. (5 points)
def mystery1(theList):
if theList == []:
return []
else:
item = min(theList)
theList.remove(item)
return [item] + mystery1(theList)
Trace:
1. theList = [2, 4, 1, 3] → item = 1 → returns [1] + mystery1([2, 4, 3])
2. theList = [2, 4, 3] → item = 2 → returns [2] + mystery1([4, 3])
3. theList = [4, 3] → item = 3 → returns [3] + mystery1([4])
4. theList = [4] → item = 4 → returns [4] + mystery1([])
5. theList = [] → returns []
Result: [1, 2, 3, 4]
Purpose: This function sorts the input list in ascending order.
3. Using ChatGPT if you wish, write a function that reverses a list using
recursion. You may NOT use the list reverse function.
(10 points)
def recursive_flip_list(lst):
if len(lst) == 0:
return []
else:
return [lst[-1]] + recursive_flip_list(lst[:-1])
# Test case
print(recursive_flip_list([1, 2, 3, 4, 5])) # Expected: [5, 4, 3, 2, 1]
4. Trace the execution of mystery3("Starts"). Show the trace and the result. Then determine
what the function is computing for any string. (Don’t explain what the code is doing –
determine what the relationship is between the input string and the Boolean returned. In
other words, what is the purpose of this function. Hint, put in print statements)
(5 points)
def mystery3(theString):
if len(theString) < 1:
return False
elif theString[0] == theString[len(theString)-1]:
return True
else:
return mystery3(theString[1:len(theString)-1])
Tracing mystery3("Starts")
Trace:
1. theString = "Starts" → theString[0] != theString[-1] → call
mystery3("tart")
2. theString = "tart" → theString[0] != theString[-1] → call mystery3("ar")
3. theString = "ar" → theString[0] != theString[-1] → call mystery3("")
4. theString = "" → return False
Result: False
Purpose: This function checks if a string is a palindrome (ignores the
first and last characters iteratively).
5. Does the following function correctly detect whether a list contains at least one positive
element? Explain why or why not. If not, explain how to fix it. (5 points)
def detectPositive(list):
for element in list:
if element > 0:
return True
else:
def detectPositive(lst):
for element in lst:
if element > 0:
return True
return False
return False
6. Assume the function in the above question works correctly or that you have fixed it. Is it
performing binary search or linear search? (5 points)
7. How much longer in the worst case does it take to search a list (assume the list is sorted) if
the number of elements being searched doubles using (5 points)
a) linear search? b) binary search?
8. Show which elements are examined in a binary search of the list. In other words, list all the
midpoints that are chosen.
[-5, -2, 0, 0.001, 1, 8.2, 8.3, 25, 99, 99, 99, 201, 10000000]
List: [-5, -2, 0, 0.001, 1, 8.2, 8.3, 25, 99, 99, 99, 201, 10000000]
a. 4.3: Midpoints → 8.2, 1, 0.001
b. 99: Midpoints → 8.2, 25, 99
c. -10: Midpoints → 8.2, -2
9. Selection Sort
a. Modify the code below so that it keeps track of the total number of comparisons
of list elements that are made while sorting the list and prints the count as well as the
sorted list. Note – for the purpose of this problem, you will be making a function
both return and print. (5 points)
def selectionSort(data):
min = index
return data
def selectionSort(data):
comparisons = 0
for index in range(len(data)):
min_index = index
for scan in range(index + 1, len(data)):
comparisons += 1
if data[scan] < data[min_index]:
min_index = scan
if min_index != index:
data[index], data[min_index] = data[min_index], data[index]
print("Sorted list:", data)
print("Total comparisons:", comparisons)
return data
b. Write a function that takes as parameter a positive integer called size and returns a
list of size random numbers (each between 0 and 100 – not including the endpoints).
(5 points)
import random
def generate_random_list(size):
return [random.randint(1, 99) for _ in range(size)]
c. Run your code in (a) on 5 random lists each of 10, 20, 40, 80 and 160 elements. (Use
the function in (b) to generate the lists.) Fill in the table below, showing the number
of comparisons. (5 points)
Using the above functions, generate lists of sizes 10, 20, 40, 80, 160 and count
comparisons.
10. Arcade. Write a program using Arcade and the code shown below to create the picture shown
below using a for loop. You can make each of the rectangles any color you like. Links to
documentation for Arcade are shown below. You will need to do a bit of research to create
the bars (filled rectangles). Each column should be 20 pixels wide and go from the top to the
bottom of the window. (10 points)
import arcade
arcade.finish_render()
arcade.run()
https://api.arcade.academy/en/latest/examples/drawing_primitives.html#drawing-primitive
https://api.arcade.academy/en/latest/api/drawing_primitives.html
import arcade
# Drawing rectangles
for i in range(0, 600, 20):
arcade.draw_rectangle_filled(i + 10, 300, 20, 600, arcade.color.BLUE)
arcade.finish_render()
arcade.run()
11. Replace the code in red with a single that has the same effect using a list comprehension.
(5 points)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
for number in numbers:
if number % 2 == 0:
result.append(number)
print(result)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = [number for number in numbers if number % 2 == 0]
print(result) # Expected: [2, 4, 6, 8]
12. Count the number of spaces in a string. Hint: create a list comprehension that returns a list of
all the spaces in the string and then find the length of it. (10 points)