# file: lists.py # author: Bob Muller # # CS1101 Computer Science I # # Code covered in class on Tuesday February 9, 2016. # add : int list -> int # def add(list): sum = 0 # sum is mutable, called a "variable" for n in list: # because its value varies. But it isn't sum = sum + n # a variable in the mathematical sense. print "So far sum = " + str(sum) return sum # recAdd : int list -> list # # Works recursively. Natural in many PLs but not the native # idiom in Python. # def recAdd(list): if len(list) == 0: return 0 else: return list[0] + recAdd(list[1:]) # find: A * A list -> int # # This is a naive definition of find, requires ~N units of work. # def find(item, list): for i in range(len(list)): if item == list[i]: return i print "Not found" return None # Redefining find to use binary search, requires only Log_2 N units # of work but requires that the elements of the input list are ordered. # # isAscending : A list -> bool # def isAscending(list): if len(list) > 1: for i in range(len(list) - 1): if list[i] > list[i + 1]: return False return True # find : A * A list -> bool # def find(item, list): assert isAscending(list), "Bad input list" lo = 0 hi = len(list) - 1 while lo <= hi: middle = (lo + hi) / 2 if item == list[middle]: return middle elif item < list[middle]: hi = middle - 1 else: lo = middle + 1 print "Not found" return None