15-112: Fundamentals of Programming and Computer Science
Quiz2



  1. Short Answer [20 pts; 10 pts each] Consider this function:
        def isMultiple(a,b):
            return (a/b*b == a)
    
    Given non-negative ints a and b, this function is supposed to return True if a is a multiple of b, and False otherwise. It mostly works, but unfortunately, it has a bug, and crashes in some cases.
    1. Fix the bug by adding a conditional expression in the space provided:
          def isMultiple(a,b):
              return (a/b*b == a) _________________________________________
      

    2. Now fix the bug a different way by adding a conditional statement in the space provided:
          def isMultiple(a,b):
      
              ________________________________________________________
              return (a/b*b == a)
      


  2. Code Tracing [20 pts]: Indicate what this will print:
    def f(x):
        while (x > 0):
            print x,
            for y in xrange(1, x, 3):
                print y,
            if (x % 3 > 0):
                print "A",
            elif (x / 3 > 0):
                print "B",
            x -= 4
            print
    print f(9)
    

  3. Reasoning Over Code [10 pts]
    Find arguments for the following function that make it return True. You only need one set of arguments for the function, even if there are multiple correct answers.
    def f(x, y, z):
        assert(x + y + z < 20)
        prev = None
        total = 10**x  # note: total is not starting at 0
        for w in xrange(x, y, z):
            if (prev != None): assert(w - prev == x)
            prev = w
            total += w
        return (total == 1018) and (y % x == 1)
    

  4. Free Response: nthFooey [50 pts]
    We will say that a non-negative int is fooey (a coined term, of course) if it is not a multiple of 10, but it is within 1 of a multiple of 10. So, 40 is not fooey, but 39 and 41 are fooey. With this in mind, write the function nthFooey(n) that takes a non-negative int n and returns the nth fooey number, counting from 0 as we usually do.

  5. Bonus/Optional: [2 pts each]
    1. Write a line or two of Python code that when executed generates this error:
         SyntaxError: name 'x' is local and global

    2. Find arguments for the following function that make it return True. For credit, be sure to show your work!
      def f(x):
          for x in xrange(x, 2*x, x/2):
              try: y = 10*y + x
              except: y = 10**(x/3)
          return (y == 1009)