CIT 591 Midterm Exam, Fall 2009 Name ______________________________

Please keep all answers short and to the point. Do not add information that is not asked for; you will lose points for getting it wrong.

1. (2 points) In IDLE, what key or key sequence is used to run a program?
F5

2. (2 points) In IDLE, what key or key sequence is used to stop a runaway (infinite loop) program?
^C or control-C          (control-F6 also works)

3. (24 points) For each of the following, write a single (that is, one) Python statement:
1. Tell the user to `Enter your name: `, then read in, and assign to a variable, a string typed in by the user.

name = raw_input('Enter your name: ')

2. Tell the user to `Enter your age: `, then read in, and assign to a variable, an integer typed in by the user.

age = input('Enter your age: ')

3. Print out, on separate lines, `Your name is var1` and `Your age is var2`, where `var1` and `var2` are the values of the two variables entered above.

4. Print out the first character (only) in the string variable `answer`.

5. Print out the last value (only) in the list variable `classes`.

 print classes[-1] OR print classes[len(classes) - 1]

6. Create, and save in a variable, a list of all the characters in the string variable `sentence`.

chars = list(sentence)

7. Create, and save in a variable, a new list containing all but the first and last values in the list variable `scores`.

 print scores[1:-1] OR print scores[1:len(scores) - 1]

8. Create, and save in variable `list2`, a copy of the list variable `list1`.

list2 = scores[:]

9. Set the variable `odd` to `True` if the integer variable `count` is an odd number, and `False` otherwise.

odd = count % 2 == 1

10. Set the variables `sum` and `product` to the sum of `x` and `y` and the product of `x` and `y`, respectively.

sum, product = x + y, x * y

11. Set the variable `mid` to the "middle" value (neither the max nor the min) of the three integer variables `x`, `y`, and `z`.

mid = x + y + z - max(x, y, z) - min(x, y, z)

12. List variable `list1` is a list of integers. Set variable `list2` to contain all the positive integers in `list1`.

list2 = filter(lambda x: x > 0, list1)    #OR
list2 = [x for x in list1 if x > 0]

4. (20 points) For each of the following, write the fewest possible Python statements to accomplish the required task. (Half credit if your answer is correct, but longer than necessary.)

1. Use a `for` loop to print the contents of list variable `list`, in order, one value per line.

 for i in list:     print i OR for i in range(0, len(list)):     print list[i]

2. Use a `while` loop to print the contents of list variable `list`, in order, one value per line.
 i = 0 while i < len(list):     print list[i]     i += 1 NO CREDIT if your code had the side effect of destroying the list in order to print out. (Same rule applies to other questions.)

3. Use a `for` loop to print the contents of list variable `list`, in reverse order, one value per line.
 for i in range(1, len(list) + 1):     print list[-i] OR for i in range(len(list), -1, -1):     print list[i]

4. Print one of the words `negative`, `zero`, or `positive`, according to whether variable `x` is less than zero, zero, or greater than zero, respectively.

if x < 0: print 'negative'
elif x == 0: print 'zero'
else: print 'positive'

5. Create a file named `foo.txt`, and write all the values in list variable `words` to it, one value per line.

f = open('foo.txt', 'w')
for word in words:
f.write(word + '\n')
f.close()

6. Write a function named `isEven` that, given a single integer parameter, returns `True` if the parameter is an even number, `False` otherwise.

 Also  acceptable: isEven = lambda n: n % 2 == 0 def isEven(n):     return n % 2 == 0

7. You are inside a test class. Write a unit test method that says calling `collatz(7)` should return `22`.

def testCollatz(self):
self.assertEqual(22, collatz(7))

8. You are inside a test class. Write a unit test method that says calling `evenRand()` should return an even number.

def testEvenRand(self):
assertTrue(evenRand() % 2 == 0

9. You are inside a test class. Write a unit test method that calls `randBuzz()`. The test should pass if `randBuzz()` returns either a positive number or the string `'buzz'`, and fail otherwise.

 def testRandBuzz(self):     result = randBuzz()     assertTrue(result > 0 or result == 'buzz') # BUT NOT def testRandBuzz(self):         assertTrue(randBuzz() > 0 or randBuzz() == 'buzz'

10. Create, and save in a variable, a 10x10 array (list of lists), all of whose values are `None`.

 Also  acceptable: Also  acceptable: a = [[[None] * 10] * 10] a = [ ] for i in range(0, 10):     a.append(10 * [None]) a =  * 10 for i in range(0, 10):     a.append(10 * [None])

5. (6 points) What gets printed by each of the following?
1. ```list1 = [1, 2, [3, 4]]
list2 = list1[:]
list1 = 5
list2 = 6
print list1, list2```
[5, 2, [6, 4]] [1, 2, [6, 4]]

2. ```list = [1, 2, 3]
list = list.append('3')
print list```
None

3. ```a = [1,2,3]
b = [1,2,3]
print a == b, a is b```
True False

6. (4 points) State, in words, what the following function does. Be precise enough that someone could use the function correctly.
```    def mystery(list):
if len(list) == 1: return list
else: return mystery(list[1:])```
The function returns the last value in the input list. The list itself is not changed.

7. (4 points) Suppose you have a `class Robot(object)`, and you want to create a class to represent a dog robot. What is the difference between saying `class Dogbot(object) `and saying `class Dogbot(Robot)` ?

The latter form inherits all the variables and methods from the Robot class.

8. (18 points) Give a short definition for each of the following:

1. recursion

The act of a function [method] calling itself.

2. side effect

A change that occurs in addition to the obvious effect. For functions [methods], this refers to any effect the function has beyond returning a value.

3. dynamic programming

Never compute anything until you need to, then remember it for use in new computations.

4. magic number

A number appearing in code with no obvious interpretation.

5. encapsulation

A.k.a. information hiding; not using the internal variables and methods of a class [or module] from outside that class.

6. refactoring

Rewriting code without changing its functionality, usually to make it more readable or more generally useful.

9. (2 points) What kind of value may not be used as a key in a dictionary? What is the reason for this restriction?

A mutable value, such as a list. Changing the value may cause it to be "lost" in the dictionary, or to collide with other dictionary keys.

10. (2 points) In pair programming, what are the two roles called?

Driver and Navigator.

11. (4 points) The DRY (Don't Repeat Yourself) principle applies to both code and data.

1. Why is it a good idea not to copy and paste code, or otherwise duplicate code? That is, what problems result from having duplicate code?

Any corrections or modifications have to be done in multiple places, and you might miss some.

2. Why is it a good idea not to have the same information represented in more than one way? That is, what problems arise?

Unless considerable care is taken, the representations may get out of sync.

12. (3 points) You have a class `Person`, with instance variables `name` and `age`. If `child` is an instance of `person`, it is legal to say `child.age += 1`, but this is poor practice. What priciple does this violate?

Encapsulation, or information hiding. This principle states that code external to a class should access the class only via its public interface.

13. (8 points) Besides having fewer bugs, programs that have been developed using TDD will generally be of higher quality. List four ways in which methods are likely to be better.
 Likely to be: More testable Smaller Single-purpose Less dependent on context Free of input/output Making less use of global variables Here are some samples of true statements that don't answer the question: Methods should be well named. TDD helps ensure continuous progress Test methods demonstrate the desired input/output Gives the programmer a clear understanding It's easier to test small methods Has fewer bugs (I said besides that) And here's an untrue statement: Methods are assured to be correct.