LMU ☀️ CMSI 1010
COMPUTER PROGRAMMING LABORATORY
Exam 2

Options with circles are single-select (exactly one), while options with squares are multi-select (zero or more).

  1. What happens if you call a recursive function without a base case?
    • It will stop after about 10 minutes with a warning and the function will raise a TimeoutError
    • It runs "forever", ultimately raising RecursionError
    • The function call will be skipped
    • Python will detect this case before you call it and crash your program with an error without ever running it
  2. For a number x, the number of times you can divide it by 2 until you reach a value <= 1 is called the "halfsies" of the number. For example, if we start with x = 10, we can halve it to 5, then 2.5, then 1.25, then we get to 0.75, which is less than 1. That was 4 halving steps, so we say halfsies(10) = 4. If we start with x = 32, we go to 16, then 8, 4, 2, 1, which means halfsies(32) = 5. This is pretty straightforward to write with a loop, but Haskellians will insist you write it recursively. Which of the following are accurate recursive implementations?
    • def halfsies(n):
          return if n <= 1 then 0 else halfsies(n / 2)+1
    • def halfsies(n):
          if n < 1:
              return 0
          else:
              return halfsies(n / 2)+1
    • def halfsies(n):
          if n <= 1:
              return 0
          return halfsies(n / 2)+1
    • def halfsies(n):
          return halfsies(n / 2)+1 if n > 1 else 0
    • def halfsies(n):
          if n <= 1:
              return 0
          else:
              return halfsies(n / 2)+1
      
  3. What does the following recursive function do?
    def mystery(a):
        return a if len(a) <= 1 else mystery(a[len(a)//2:]) + mystery(a[:len(a)//2])
    
    • It interleaves all the values of the list
    • It reverses the list
    • It puts the last half of the list before the first half
    • It loops forever because the recursion does not have a base case
  4. In the Tower of Hanoi lab, moving 3 disks takes 7 moves. How many moves does it take to move (a) 4 disks, (b) 10 disks, (c) n disks?
  5. What does count(4) return?
    def count(depth):
        if depth == 0:
            return 1
        return 1 + count(depth - 1) + count(depth - 1)
    
  6. Which of the following are true about recursion, as discussed in class?
    • Every recursive call should move closer to a base case
    • A recursive function can have more than one base case
    • Recursion is always better than a loop
    • Recursion tends to shine when a function calls itself more than once, as in Tower of Hanoi and fractal trees
    • A recursive function must take exactly one parameter
  7. Without using any loops (no for, no while, no comprehensions), write a recursive function called count_vowels that returns the number of vowels (a, e, i, o, u, lowercase only) in a string. For example, count_vowels("banana") is 3 and count_vowels("") is 0.
  8. In the Family Archive lab, if the Person class did not define a __str__ method, what would print(Person("Alice")) show?
    • Alice
    • Person("Alice")
    • Something like <__main__.Person object at 0x104f2ad50>
    • Nothing, because Python raises a TypeError
  9. Assume the Person class has the method
    def is_sibling_of(self, other):
        return self.mom is other.mom or self.dad is other.dad
    
    and we write:
    adele = Person("Adele", mom=Person("Marie"), dad=Person("Pierre"))
    joseph = Person("Joseph", mom=Person("Marie"), dad=Person("Pierre"))
    
    What is the value of adele.is_sibling_of(joseph), and why?
    • True, because both people have a mom named Marie and a dad named Pierre
    • False, because four different Person objects were created for the parents, so Adele's mom is not the same object as Joseph's mom
    • False, because is only works on numbers and strings
    • An error is raised, because self was never passed in
  10. The method call adele.is_sibling_of(joseph) is a shortcut for which of the following?
    • is_sibling_of(joseph, adele)
    • Person.is_sibling_of(adele, joseph)
    • Person.is_sibling_of(self, adele, joseph)
    • joseph.is_sibling_of(adele)
  11. Which of the following are needed in order to write a dataclass like the Card class from The Real Deal lab?
    • from dataclasses import dataclass
    • The @dataclass decorator just above the class
    • Fields written with type annotations, like rank: int
    • An __init__ method that assigns self.suit and self.rank
    • A __post_init__ method
  12. When is a dataclass's __post_init__ method called?
    • Only when you call it yourself, as in card.__post_init__()
    • Right before the attributes are assigned, so it can choose their values
    • Right after the generated __init__ assigns the attributes
    • When the program finishes
  13. Given
    from dataclasses import dataclass
    
    @dataclass(frozen=True)
    class Card:
        suit: str
        rank: int
    
    a = Card("S", 12)
    b = Card("S", 12)
    
    which of the following are true?
    • a == b is True
    • a is b is True
    • a.rank = 13 raises an error
    • Card("S") raises an error
    • Card(rank=12, suit="S") makes a card equal to a
  14. Write a dataclass called Color with fields red, green, and blue. Every color created must be a legal RGB color: if any field is not an int, raise a TypeError, and if any field is outside the range 0 to 255, raise a ValueError. Include the import.
  15. Match each RGB tuple with its color, by writing in each blank one of the following: K for black, W for white, R for red, G for green, B for blue, Y for yellow, A for gray
    _______ (0, 0, 255)
    _______ (255, 255, 0)
    _______ (0, 0, 0)
    _______ (128, 128, 128)
    _______ (0, 255, 0)
    _______ (255, 255, 255)
  16. Which of the following are legal RGB color tuples?
    • (12, 200, 255)
    • (256, 0, 0)
    • (0, 0)
    • (0, 0, 0)
    • (100, -5, 100)
  17. Given
    def f(s):
        try:
            n = int(s)
            print("A")
            print(100 // n)
        except ValueError:
            print("B")
        except ZeroDivisionError:
            print("C")
    
    what is printed by each of the following calls?
        f("5")      _____________________________
        f("0")      _____________________________
        f("dog")    _____________________________
    
  18. Following the rule "TypeError for the wrong type, ValueError for the right type but a bad value," write T or V in each blank for the error that a well-written Card class (suits "S", "H", "D", "C", ranks 1 through 13) should raise:
    _______ Card("X", 5)
    _______ Card("S", "5")
    _______ Card("H", 14)
    _______ Card(7, 7)
    _______ Card("D", 0)
  19. If a program is run with python hanoi.py 4, which expression gives the number of disks as an integer?
    • sys.argv[0]
    • sys.argv[1]
    • int(sys.argv[0])
    • int(sys.argv[1])
    • int(sys.argv)
  20. Write a complete Python program that prints the sum of its command line arguments, treated as integers. For example, python total.py 3 10 -2 prints 11, and python total.py prints 0. If any argument is not an integer, print All arguments must be integers instead of a sum.