Courses/Computer Science/CPSC 203/CPSC 203 Template/Fall 2009 Teaching Assistants/F09 Thomas Burt/Programming Review/Answers
From wiki.ucalgary.ca
< Courses | Computer Science | CPSC 203 | CPSC 203 Template | Fall 2009 Teaching Assistants | F09 Thomas Burt | Programming Review
Contents
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 == 1: 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 a = p * (1 + r / n) ** (n * 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 mul5(lower, upper): print "Numbers that are divisible by 5 are:" sum=0 for x in range(lower,upper+1): if (x%5==0): print x else: sum=sum + x print "Sum of numbers that are multipliers of 5 is", sum
Code Writing
def reorderByOdds( list ): evens = [] odds = [] for i in list: if i % 2 == 0: evens.append(i) else: odds.append(i) evensLen = len(evens) oddsLen = len(odds) output = [] evens.reverse() odds.reverse() for i in range(0, min(evensLen, oddsLen)): output.append(odds.pop()) output.append(evens.pop()) if( len(evens) != 0): output.extend(evens) elif(len(odds) != 0): output.extend(odds) return output