# file: lists.py # # author: Bob Muller # date: November 6, 2007 # # This module has some simple functions operating on lists. # These functions were covered in class on Nov. 6, 2007. import random def length(lst): if lst == []: return 0 else: return 1 + length(lst[1:]) # A series of three -many- functions which return lists of various # kinds. # def manyOnes(n): if n == 0: return [] else: return [1] + manyOnes(n - 1) def manyOf(m,n): if m == 0: return [] else: return [n] + manyOf(m - 1,n) def manyRandoms(m,n): if m == 0: return [] else: return [int(n * random.random())] + manyRandoms(m - 1,n) # printAll accepts a list and prints all the elements, one per line. # def printAll(lst): if lst == []: return else: print lst[0] printAll(lst[1:]) # member accepts an item and a list and returns True if the item # is in the list. Otherwise it returns False. # def member(item, lst): if lst == []: return False else: return (item == lst[0]) | member(item, lst[1:]) # rember accepts an item and a list and returns the list with the # first occurrence of the item removed. # def rember(item, lst): if lst == []: return [] else: if item == lst[0]: return lst[1:] else: return [lst[0]] + rember(item, lst[1:]) # countAll accepts an integer m and a list of integers lst. It returns # the number of times that m occurs in lst. # def countAll(m,lst): if lst == []: return 0 else: if m == lst[0]: return 1 + countAll(m,lst[1:]) else: return countAll(m,lst[1:]) # frequency accepts two integers m and n. It first generates a list of m # random numbers. Each random number is between 0 and n - 1. frequency # returns a list of frequency counts of the numbers. # # NB: This function is a little different than the one handed out and # covered in class on Tuesday Nov. 6. # def frequency(m,n): # generate a list of n zeros. This list will be used as counters. # counts = manyOf(n,0) i = 0 while i < m: j = int(random.random() * n) counts[j] = counts[j] + 1 i = i + 1 return counts