Practice Problems - Set 1

These problems are for practice. They are optional, but you are encouraged to complete them and discuss them with members of the course staff during lab and office hours.

Some of these problems will appear on the final exam, and others are very similar to final exam problems. However, not all final exam problems will be telegraphed.

Problem 0

What is the printed output of this program?

x = [1, 3, 4, 5]

for j in range(x):
  print(x[j])

Problem 1

What is the printed output of this program?

x = [1, 2, 4, 5]

for i in range(len(x)):
  print(x[2])

Problem 2

S = ['first', 'thousand', 'kilometers']

for s in S:
  if len(s) > 8:
    print(s)

Problems 3-5 reference the code below

def length_list(input_list):
  output_list = []
  for k in range(len(input_list)):
    output_list[k] = len(input_list[k])
  return output_list

Problem 3

The function length_list is intended to take as argument a list of strings and return a list of the lengths of each string. For example:

  • length_list(['harvest', 'moon']) should return [7, 4].
  • length_list(['lullaby', 'as', 'genre']) should return [7, 2, 5].
  • length_list(['wild', 'sheep', 'chase']) should return [4, 5, 5].

The function, as written, does not do this. Modify line 4 of the function so that it works correctly.

Problem 4

Line 4 of the function, as written, causes an error when called with an argument that is a list of strings. However, there are some arguments which, when the function is called on them, do not result in errors.

What is one of those arguments? Restated, what, when passed into length_list as the argument input_list, does not result in an error.

Provide both the argument and the function’s return value.

Problem 5

Rewrite the function so that the shortest string’s length is subtracted from each length in the output list.

  • length_list(['harvest', 'moon']) should return [3, 0].
  • length_list(['lullaby', 'as', 'genre']) should return [5, 0, 3].
  • length_list(['wild', 'sheep', 'chase']) should return [0, 1, 1].

Problem 6

(This problem is slightly harder than what will appear on the final exam).

def in_forty_five(hour, minute):
    minute += 45
    if minute > 60:
        hour += 1
    return str(hour) + ":" + minute

The function in_forty_five is intended to take two integer arguments: hour and minute, corresponding to some clock time. The function is intended to return a string of the input time plus 45 minutes, formatted as follows:

  • in_forty_five(6, 30) should return "7:15"
  • in_forty_five(8, 5) should return "8:50"
  • in_forty_five(12, 10) should return "12:55"
  • in_forty_five(12, 20) should return "1:05"
  • in_forty_five(9, 15) should return "10:00"

Problem 7

What is the printed output of this program?

R = ['an', 'underground', 'river']

for r in R:
  if r == 'underground':
      r = 'exquisite'

print(R)