EE1021 Homework 2: Functions and Lists

Core: W1–W2, P1–P5. Optional: X1–X3. Not graded, but required on CATS.

Warm-up

W1. Predict the three lines before running. Then run and compare.

values = [5, 10, 15]
copy_a = values
copy_b = values.copy()
values.append(20)
copy_a[0] = 1
print(values)
print(copy_a)
print(copy_b)

W2. average([2, 4, 6]) should return 4.0. Fix the bug.

def average(values):
    total = 0
    for v in values:
        total = total + v
        return total / len(values)

Write the functions

P1. Use your own student number as a string.

  • digits_of("2500001234") → [2, 5, 0, 0, 0, 0, 1, 2, 3, 4]
  • digit_stats(digits) takes that list of digits and returns the tuple (smallest, largest, average), average rounded to 2 decimals.

P2. limit_readings(readings, low, high) returns a new list: values below low become low, values above high become high. Do not change the input. count_changed(original, limited) returns how many values changed.

raw = [4.10, 4.92, 5.08, 5.70, 4.97]
limit_readings(raw, 4.75, 5.25)   # [4.75, 4.92, 5.08, 5.25, 4.97] -> 2 changed

P3. compress(values) replaces each run of equal values next to each other with one tuple (value, how many times in a row). expand(pairs) does the reverse and rebuilds the original list.

compress([0, 0, 0, 1, 1, 0])        # [(0, 3), (1, 2), (0, 1)]   three 0s, two 1s, one 0
expand([(0, 3), (1, 2), (0, 1)])    # [0, 0, 0, 1, 1, 0]

Each tuple stores two numbers. When does the compressed list store more numbers than the original?

P4. second_largest(values) returns the second largest different value. No sort, sorted, max or min; go through the list once.

second_largest([3, 8, 1])      # 3
second_largest([5, 5, 3])      # 3
second_largest([-4, -1, -7])   # -4
second_largest([7, 7])         # None

P5. merge_sorted(a, b): a and b are sorted. Return one new sorted list. No sort or sorted; do not change a or b.

merge_sorted([1, 4, 9], [2, 3, 10, 12])   # [1, 2, 3, 4, 9, 10, 12]
merge_sorted([1, 2], [2, 3])              # [1, 2, 2, 3]
merge_sorted([], [5, 6])                  # [5, 6]

Optional

X1. find_spikes(readings, limit) returns the indices of values that differ from both neighbours by more than limit. The first and last values have only one neighbour, so they are never spikes.

find_spikes([5.0, 5.1, 7.9, 5.0, 5.2, 2.1, 5.1], 1.0)   # [2, 5]

X2. Write a function with a list and a loop for a problem from another course you take this term. Show two test runs.

X3. After a = [1, 2] and b = a: does a += [4] change b? Does a = a + [5]? Find out and write the rule in one sentence.