CS 116: Introduction to Computer Science 2

CS 116 Tutorial 6: Iteration


Reminders: Assignment 06 is due on Wed, March 11th at 10AM


  1. Write a function all_same_type that consumes a list, called lst, and produces True if all members of that list are of the same type, else False.

    For example:

      all_same_type([2, 5, 3]) => True
      all_same_type([2, "R", 4.56]) => False

  2. Write a Python function max_even_sum that consumes a nonempty list of lists of positive integers, lst. Evaluate in lst is a list of positive integers. It computes the sum of the even integers in each of the element lists in lst, and produces the largest out of these sums. If a sublist contains no even integers, its sum is zero.

    For example:

      max_even_sum([[], [3], [2,4,6]]) => 12

  3. Write a Python function sum_digits that consumes a Nat (called n), and returns a number represents the summation of its digits.

    For examples:
    sum_digits(1)=>1
    sum_digits(55)=>10

  4. Write a Python function that consumes a natural number n and produces a list of strings. The produced list will look like

    ["", "1", "22", "333", "4444", "55555", ... , "nnnnn...nnnn"]

    where the last element is the number n repeated n times.

    For examples:
    make_list(0) => [""]
    make_list(3) => ["", "1", "22", "333"]

  5. Write a function called valid_input that consumes a string to be used as the prompt, prompt, and a list of strings of valid inputs, valid, and a positive integer max_guess.
    The function should continuously prompt the user for input until the user enters a value in the list valid, and then produces that value, or print a message when maximum number of guess is reached. If the user enters an invalid value, the function will let them know by printing: "Invalid input. Try again." to the screen. If maximum number of guess is reached, the function will print "Maximum number of guess is reached"

    For example:
    If the user enters "6", "5", and "3", valid_input("Enter a digit < 5: ", ["0", "1", "2", "3", "4"], 5) => "3" and the following is printed:
    Enter a digit < 5: 6
    Invalid input. Try again
    Enter a digit < 5: 5
    Invalid input. Try again
    Enter a digit < 5: 3

    Note: You may assume that the user enters input that is the correct type.