Sei sulla pagina 1di 2

"""

Imperative Programming
Introduction to Computer Science cs105
Haverford College

Complete the following functions using iteration/loops


(i.e., if you see a recursive version, replace it with one
that uses a loop).
Here are a few doctests to help with the definition of each function.
>>> assert sumlist([4, 3, 6, -1]) == 12
>>> assert averagelist([4, 3, 6, -1]) == 3
>>> assert power(2,5) == 32
>>> assert reverse("redrum") == "murder"
"""

# what film?

from logic import *


# returns the sum of a list of numbers
def sumlist(number_lst):
precondition(type(number_lst) == type([]))
total = 0
while len(number_lst) > 0:
precondition ((type(number_lst[0]) == type(2)) or (type(number_lst[0]) ==
type(2.2)))
total = total + number_lst[0]
number_lst = number_lst[1:]
return total
# returns the average of a list of numbers
def averagelist(number_lst):
precondition(type(number_lst) == type([]))
divide_by = len(number_lst)
avg = 0
while len(number_lst) > 0:

avg = avg + number_lst[0]


number_lst = number_lst[1:]
return avg/divide_by

# returns base^exp
def power(base, exp):
precondition((type(base) == type(2)) or (type(base) == type(2.2)))
precondition(type(exp) == type(2))
precondition(exp >= 0)
answer = base
while exp > 1:
exp = exp - 1
answer = answer * base
return answer
# returns the original string backwards
def reverse(s):
precondition(type(s) == type("some string"))
inverted_s = ""
while len(s) > 0:
inverted_s = inverted_s + s[-1]
s = s[:-1]
return inverted_s
if __name__ == "__main__":
import doctest
doctest.testmod()
print "looping done"

Potrebbero piacerti anche