computer science

profiletwincarlos23
HW52.pdf

Homework 5

Due September 28, 2021, Last day to turn in without penalty: October 7

For a Google Colab starter file, go to https://colab.research.google.com/drive/1_ wgJnxUr6S2y6PZ9BnITAlqnozGhiNE8. Do all questions in the same notebook (but use different cells), so that you only need to share and enable one link in your submission.

1. For each of the following problems, describe in words, not code what numbers each of the following lists consists of. Make sure you include the first and last number of the list in your description. You may run the code in order to verify your results.

(a) range(10)

(b) range(3, 52)

(c) range(5, 99, 2)

(d) range(99, 5, -2)

(e) range(5, 99, -2)

2. Write a program that takes a list of strings (words) and prints the longest word. For example, if words = [’cat’,’dog’,’goat’,’elephant’], print ’elephant’. If there is a tie, you may print any word that is the longest. For example, if words = [’cat’,’dog’], you may print either ’cat’ or ’dog’.

3. Write a program that takes a list, “nums”, consisting of 2n elements in the form [x1, x2, . . . , xn, y1, y2, . . . , yn], and return the list in the form [x1, y1, x2, y2, . . . , xn, yn]. For example, if nums = [5, 8, 1, 4, 2, 3], the program should output [5, 4, 8, 2, 1, 3]. Hint: Find the middle element. Split the list into two sub-lists, create an empty list and then append one element from each sub-list until you get to half the length of the list.

4. Given a list of numbers, “nums”, and another number, “indicator”, count how many numbers in the list are less than “indicator”. For example, if nums = [5, 1, 2, 7, 4, 3, 11] and indicator = 4, then output 3, since [1, 2, 3] are all less than 4 (note that 4 is not less than 4).

5. Identify and correct the errors in the following code, which is supposed to take a list of numbers and print the numbers that are divisible by 3. For example, if nums = [1, 4, 5, 7, 9, 12, 13], then print the numbers 9 and 12 (code on the next page).

1

def print_div_by_3():

for num in nums:

if num // 3 = 0:

li.append(num)

return li

nums = [1, 4, 5, 7, 9, 12, 13]

print_div_by_3

2