Data Structures and Algorithms (DSA27) · Week 3

Recursion · data structures and classes in Python (Lecture 03, Lab 03)

These quizzes are for self-study. Your answers are saved on this device only and are not sent anywhere.

Score: 0 / 44 · Answered: 0

  1. W3-M01 Recall

    Every correct recursive function needs:

  2. W3-M02 Apply

    With def factorial(n): return 1 if n == 0 else n * factorial(n - 1), what does factorial(-1) do?

  3. W3-M03 Recall

    By default, CPython stops a recursion at a depth of about:

  4. W3-M04 Apply

    How much stack space does factorial(n) use?

  5. W3-M05 Apply

    T(n) = T(n/2) + c solves to:

  6. W3-M06 Apply

    T(n) = 2T(n-1) + c solves to:

  7. W3-M07 Apply

    T(n) = T(n-1) + cn solves to:

  8. W3-M08 Apply

    How many moves does Towers of Hanoi need for 5 disks?

  9. W3-M09 Apply

    How many subsets does a set of 4 items have (including the empty set and the whole set)?

  10. W3-M10 Apply

    How many orderings (permutations) do 4 distinct items have?

  11. W3-M11 Apply

    How many calls in total does the naive fib(5) make (counting the first)?

  12. W3-M12 Explain

    Fast power written as half = power(x, n // 2) * power(x, n // 2) (then × x if n is odd). Its cost is:

  13. W3-M13 Explain

    list_max(values) recurses on values[1:]. Its running time is:

  14. W3-M14 Recall

    Memoisation means:

  15. W3-M15 Explain

    hanoi(20) makes over a million calls. At most how many frames are on the call stack at the same time?

  16. W3-M16 Apply

    What does f(3) print?

    def f(n):
        if n == 0:
            return
        print(n, end=" ")
        f(n - 1)
        print(n, end=" ")
  17. W3-M17 Explain

    What should subsets([]) return?

  18. W3-M18 Recall

    Tail-call optimisation in Python:

  19. W3-M19 Apply

    marks = [3, 1, 2]; result = marks.sort(). What is result?

  20. W3-M20 Recall

    What is type({})?

  21. W3-M21 Recall

    The average cost of x in s for a Python set of n items is:

  22. W3-M22 Explain

    What is wrong with this class?

    class Dog:
        tricks = []
        def __init__(self, name):
            self.name = name
        def add_trick(self, trick):
            self.tricks.append(trick)
  23. W3-M23 Recall

    Calling a function that contains yield:

  24. W3-M24 Explain

    Why should a queue not be a Python list used with pop(0)?

  25. W3-M25 Apply

    What is counts after this?

    counts = {}
    for w in "a b a".split():
        counts[w] = counts.get(w, 0) + 1
  26. W3-M26 Apply

    The recurrence of naive Fibonacci, T(n) = T(n-1) + T(n-2) + c, grows like:

  27. W3-M27 Apply

    Lecture 03's to_binary:

    def to_binary(n):
        if n < 2:
            return str(n)
        return to_binary(n // 2) + str(n % 2)

    What does to_binary(6) return?

  28. W3-M28 Apply

    With the course gcd (return a if b == 0, else return gcd(b, a % b)), how many calls does gcd(48, 18) make in total, counting the first?

  29. W3-M29 Explain

    In binary_strings, the base case is changed from return [""] to return []. What does binary_strings(2) return now?

    def binary_strings(n):
        if n == 0:
            return []
        shorter = binary_strings(n - 1)
        return ["0" + s for s in shorter] + ["1" + s for s in shorter]
  30. W3-M30 Explain

    flatten descends only into items for which isinstance(item, list) is true, not into everything that is iterable. Why?

  31. W3-M31 Recall

    With the course's fast power (one call on exponent // 2, base case exponent == 0), at most how many frames of power are on the call stack at once during power(2, 1000)?

  32. W3-M32 Recall

    The memoised fib_memo(30) of Lecture 03 (memo in an Array) makes how many calls in total, counting the first?

  33. W3-M33 Explain

    The course merge_sorted is called on two sorted lists of 600 numbers each, and raises RecursionError. Why?

  34. W3-M34 Explain

    merge_sorted compares the heads with left[0] <= right[0]. What would change if it used < instead?

  35. W3-M35 Apply

    sum_digits(n) makes one call on n // 10 and does O(1) work besides. Its running time, in terms of the number n, is:

  36. W3-M36 Apply

    With Lecture 03's depth (0 for a non-list; otherwise 1 + the deepest item, where an empty list has depth 1), what is depth([1, [2, [3]], []])?

  37. W3-M37 Recall

    In the recursive solution of Towers of Hanoi with n disks, how many times does the largest disk move?

  38. W3-M38 Apply

    In the moves returned by hanoi(n), how many times does the smallest disk move?

  39. W3-M39 Explain

    Why is gcd easy to rewrite as a plain while loop, while hanoi would need an explicit stack?

  40. W3-M40 Explain

    Lecture 03's array_max(arr, i=0) recurses on i + 1 and never slices. What happens when it is called on a course Array of 5,000 numbers?

  41. W3-M41 Apply

    The course subsets:

    def subsets(items):
        if not items:
            return [[]]
        rest = subsets(items[1:])
        return rest + [[items[0]] + subset for subset in rest]

    What does subsets([1, 2]) return, in this order?

  42. W3-M42 Recall

    Which of these can be used as a dict key or a set member?

  43. W3-M43 Explain

    What does this print?

    t = (1, [2])
    t[1].append(3)
    print(t)
  44. W3-M44 Apply

    What does this print?

    def countdown(n):
        while n > 0:
            yield n
            n -= 1
    
    g = countdown(3)
    next(g)
    print(list(g))

36 marks

Written questions

10 written questions (36 marks). Write your answer first, then open the model answer and its marking points, and mark yourself honestly: each point is worth about one mark.

Written total: 0 / 36

  1. W3-E1 Apply 4 marks

    Draw the call stack at every step of factorial(3), from the first call until the final value is returned. Label winding, the base case, and unwinding, and show the value each frame returns.

  2. W3-E2 Explain 4 marks

    Explain why the naive recursive Fibonacci takes exponential time, using a recursion tree. Show how memoisation fixes it, and state the new time and space costs.

  3. W3-E3 Explain 3 marks

    When should you prefer recursion, and when a loop? Include two concerns that are specific to Python.

  4. W3-E4 Explain 4 marks

    Describe the recursive strategy for Towers of Hanoi. Write its recurrence, solve it, and explain why no algorithm can use fewer moves.

  5. W3-E5 Explain 3 marks

    Explain "trust the recursion" and how it relates to mathematical induction.

  6. W3-E6 Explain 4 marks

    For each job, choose list, tuple, set or dict and justify by cost: (a) the marks of a class, in the order entered; (b) checking whether a student ID has already been registered; (c) looking up a student's name by ID; (d) one student's (ID, name, mark), used as a key elsewhere.

  7. W3-E7 Explain 4 marks

    hanoi(20) makes over a million calls, yet it never has more than about 20 frames on the call stack. Explain why the space a recursion needs is set by its depth and not by its number of calls. Give the depth of factorial(n), of the fast power(x, n) and of hanoi(n), and explain why raising sys.setrecursionlimit is not the right fix for a recursion that must go 100,000 deep.

  8. W3-E8 Explain 4 marks

    Three versions of power(x, n): (i) x * power(x, n - 1); (ii) half = power(x, n // 2), then half * half (× x if n is odd); (iii) power(x, n // 2) * power(x, n // 2) (× x if n is odd). For each, write the recurrence and its solution, and say what happens for n = 4,096.

  9. W3-E9 Explain 3 marks

    Rewrite gcd as a loop, and explain why that rewrite is easy. Explain why rewriting hanoi without recursion is harder, and what the loop version must keep for itself.

  10. W3-E10 Explain 3 marks

    Explain why binary_strings(0) must return [""], and subsets([]) must return [[]], rather than []. What goes wrong with [], and how many results do binary_strings(n) and subsets of n items return?