CIT 591 Midterm

Name ________________________________________
  1. (5 points) Write a function letter_count to count the number of letters in a string, returning the result as an integer. You may wish to use the isalpha method for characters. Part of the function has been provided for you.
    def letter_count(s):
        count = 0
    for char in s:
    if char.isalpha():
    count += 1

    return count

  2. (5 points) Write a function extremes that, given a nonempty list of integers, returns the pair (least, greatest), where least is the smallest number in the list, and greatest is the largest number in the list. You may use Python's built-in functions in your function definition.
    def extremes(lst):
    return (min(lst), max(lst))

  3. (5 points) Give an English description of what the following function does.
    import random
    def points(n):
        directory = {}
        for i in range(0, n):
            pname = chr(ord('a') + i)
            x = 1000.0 * random.random()
            y = 1000.0 * random.random()
            directory[pname] = (x, y)
        return directory
    Returns a dictionary in which the keys are n successive characters beginning with 'a', and each value is a pair of floating-point numbers in the range 0.0 to 1000.0.

  4. (15 points) Each of the following pieces of code has an error. Tell what the error is and how to correct it.

    1. # nums is a list of integers. Add the first and last numbers in the list,
      # and append the result to the list.
      nums = nums.append(nums[0] + nums[-1])

      The error is that the append function returns None.
      The correction is to eliminate the "nums =" part.

    2. # Delete negative numbers from the list
      for i in lst:
          if lst[i] < 0:

      Two errors: Confusing values with indices, expecting indices to remain meaningful when list is changing.
      Most "solutions" don't work. One that does is creating a new list,
              lst2 = []
              for i in lst:
                   if i >= 0: lst2.append(i)
               lst = lst2
      Even better, replace these lines with a filter:
            lst = filter(lambda x : x >= 0, lst)

    3. # print the average of the three given numbers a, b, c
      print "The average is " + (a + b + c) / 3

      The error is adding a number to a string. Another possible error is integer division, if a, b, c are all integers.
      One correction is to convert the number to a string,
            print "The average is " + str( (a + b + c) / 3.0)
      A simpler correction is to use a comma instead of a plus,
           print "The average is", (a + b + c) / 3.0
      In both cases, replace the 3 with 3.0.

  5. (5 points) Given the following function:
    def foo(s):
        d = {}
        for ch in s:
            v = d.get(ch, 0)
            d[ch] = v + 1
        return d
    what is returned by the call foo("sassafras") ?

    {'a': 3, 's': 4, 'r': 1, 'f': 1}, in some order.

  6. (5 points) Given the following function:
    def letters(s):
        ss = []
        for ch in s:
            if ch.isalpha():
        return ss
    what is returned by the call letters("1 and 2 and 3") ?

    ['a', 'n', 'd', 'a', 'n', 'd']

  7. (5 points) Given the following function:
    def lets(s):
        return "".join(filter(lambda x: x.isalpha(), list(s)))
    what is returned by the call lets("1 and 2 and 3") ?


  8. (5 points) Given the following function:
    def f(n):
        return [foo, points, letters, lets][n]
    what is returned by the call f(1) ?

    This returns the points function; if printed, it would look something like
    <function points at 0x0000000002644358>

  9. (10 points) Suppose you are defining a class Circle, and every object of this class must have three values: The x and the y coordinates of the circle's center, and the radius of the circle.
    1. Write the constructor that you would put in this class.

      def __init__(self, x, y, r):
          self.x, self.y, self.radius = x, y, r

    2. Use the above constructor to create a circle named unitCircle with radius = 1 and center at the origin (x = y = 0).

      c = Circle(0, 0, 1)

  10. (5 points) What is the purpose of the following code in a Python program?
     if __name__ == '__main__':
    If the file is loaded directly, the main() function will be executed automatically; but if loaded indirectly (say, from a unit test file), it won't be.

  11. (5 points) Use a list comprehension to assign to the variable oddCubes the cubes of the odd integers between 0 and100.

    oddCubes = [x * x for x in range(1, 100, 2)]
    oddCubes = [x * x for x in range(1, 100) if x % 2 != 0]

  12. (15 points) Assume that you have written a class ListUtils to provide a number of operations on lists. This class is in the file In the following three questions you will write a complete class to test one of the functions in ListUtils.

    1. Write the necessary import statements and the class header for a class named ListUtilsTest.

      import unittest
      from listutils import *
      class ListUtilsTest(unittest.TestCase):

    2. Write a test for the function duplicate(lst) which is supposed to return a shallow copy of the list given as a parameter.

          def testDuplicate(self):
              lst = [3, 1, 4, 1, 6]
              self.assertEquals(lst, duplicate(lst))
              self.assertIsNot(lst, duplicate(lst))

    3. Write the statement or statements necessary to perform the tests in the ListUtilsTest class.


  13. (5 points) Given the function
    def fiddle(index, lst):
        index += 1
        lst[index] += 1
    what will be printed by
    n, nums = 3, range(1, 6)
    fiddle(n, nums)
    print n, nums
    3 [1, 2, 3, 4, 6]

  14. (5 points) In IDLE, what is the value of the variable _ (a single underscore)?

    The value of the previous expression.

  15. (5 points) Give one way in which using TDD, Test Driven Design, may improve the style (not the correctness) of a program.