Courses/Computer Science/CPSC 203/CPSC 203 Template/Fall 2009 Teaching Assistants/F09 Thomas Burt/Programming Review/Exercises

= Code Repairing = Fix the following code samples so that they work correctly:

def countOdds(list) total_odds = 0 for i in list: if i % 2 == 0: total_odds+=1 return total_odds

def foo(x): if x << 0 print x "is less than zero" elif x == 0 print x "is equal to zero" else print x, "is not less than zero

For this one, check that the formula is correct and that the correct value is returned def compoundInterest(p, r, n, t) a = 0 #the exponent operator is ** a = (p * (1 + r)/n) ** n*t return t

= Code Modifying =

Right now this function prints out and then sums up numbers that are divisible by 3. The input is a lower and upper bound on the range of numbers to check.

Change this function so it checks for numbers divisible by 5. Also, print out the sum of the numbers that are not divisible by 5.

def mul3(lower, upper): print "Numbers that are multipliers of 3 are:" sum=0 for x in range(lower,upper+1): if (x%3==0): print x     sum=sum + x  print "Sum of numbers that are  multipliers of 3 is", sum

= Code Writing =

If you understand how to do this one, you should be OK!

Write a function that takes in a list of numbers as input, and outputs a list. The numbers in the output list should all be taken from the input list, except they should alternate between even numbers and odd numbers. In the case that the input list has more even (or odd) numbers, it's okay to just place the extras at the end. HINT: you might want to use functions from page 65 in the text.

Example input/output: >>> l = [1, 2, 3, 4] >>> reorderByOdds(l) [1, 2, 3, 4] >>> l = [1, 1, 2, 3, 3, 6, 4] >>> reorderByOdds(l) [1, 2, 1, 6, 3, 4, 3]