Skip to main content

Day 26 - Transition to Python 3

Skills: 9

Pre-reading: 9.1.8 (skip 9.1.8.5, since we've already seen that on Day 14).

Intro (10 mins)

  • Today we focus on traversing and transforming lists in Python using for loops, and compare with Pyret's approaches.
  • Example: Summing a List
    • Python:
      def sum_list(num_list: list) -> float:
      """Returns the sum of all numbers in the list."""
      run_total = 0
      for num in num_list:
      run_total = run_total + num
      return run_total

      def test_sum_list():
      assert sum_list([1, 2, 3]) == 6
      assert sum_list([]) == 0
    • Pyret (for each loop):
      fun sum-list-for(numlist :: List<Number>) -> Number block:
      doc: "Returns the sum of all numbers in the list using a for loop."
      var sum = 0
      for each(n from numlist):
      sum := sum + n
      end
      sum
      where:
      sum-list-for([list: 1, 2, 3]) is 6
      sum-list-for([list: ]) is 0
      end
    • Pyret (recursive):
      fun sum-list(numlist :: List<Number>) -> Number:
      doc: "Returns the sum of all numbers in the list."
      cases (List) numlist:
      | empty => 0
      | link(fst, rst) => fst + sum-list(rst)
      end
      where:
      sum-list([list: 1, 2, 3]) is 6
      sum-list([list: ]) is 0
      end

Class Exercises (35 mins)

For each function, follow the full design recipe: type signature, docstring, tests, and code.

  • Design a Python function product_list(nums: list) -> float that returns the product of all numbers in the list (1 for empty list).

  • Design a Python function count_occurrences(items: list, target) -> int that returns how many times target appears in the list.

  • Design a Python function filter_by_prefix(words: list, prefix: str) -> list that returns a list of all words starting with the given prefix. In Python, if you have a string s, you can check if it starts with a prefix using s.startswith(prefix).

  • Design a Python function reverse_list(lst: list) -> list that returns a new list with the elements in reverse order (do not use reversed() or [::-1]).

  • Design a Python function all_with_letter(words: list, letter: str) -> list that returns all words containing the given letter. In Python, you can check if a string contains a letter using letter in word.

  • For one of the above problems, write the equivalent function in Pyret using both recursion and a for each loop.

Wrap-up (5 mins)

  • Python for loops and mutable accumulators are a common way to process lists. While recursion can be done, it is less idiomatic in Python.
  • Pyret supports both recursion and iteration; both approaches have strengths.