You might have noticed by now, that your code does not always work the way you intend at the first attempt you make at writing it. This is quite normal, so you need to learn how to deal with this and how to fix it.
Errors in software are known as "bugs" and removing them is known as "debugging".
The first step in debugging is finding out that there is a problem to begin with.
Assuming we find that there is an error, the next step is then to identify what the error is, and then the final step is to modify the code to remove the error.
Of these three steps, the hardest by far is step two. But do not despair, it is hard but not impossible, and it gets easier with practice.
The easiest approach is just to break down your code into smaller pieces, add some print statements between the pieces so you can see what the various steps are doing, and then identify the point in the code where the code is no longer in the state you expected.
In the following exercises, you are presented with functions that are not doing what they are intended to do.
Exercises
The following functions contain mistakes and do not do what they are supposed to. Fix them so they do. At the beginning of of each function is a string describing the function. These strings do not do anything other than serve as documentation for the functions.
contains(lst, n)
def contains(lst, n): """ Take a list of integers lst and a single integer n as arguments. Returns True if n is an element in lst. """ for e in lst: if e == n: return True else: return False
Should work like this:
>>> contains([4, 3, 7, 13], 7)
True
frequencies(counts):
def frequencies(counts): """ Takes a list of integers as argument. Returns a list relative frequencies. """ total = sum(counts) frequencies = [] for count in counts: frequencies.append(float(count/total)) return frequencies
Should work like this:
>>> frequencies([4, 3, 7]) [0.2857142857142857, 0.21428571428571427, 0.5]
containsNoDivisor
def containsNoDivisor(n, ps): '''n is an integer and ps is a list of integers. Returns True if and only if there is no integer in ps that divides n. ''' for p in ps: if n % p == 0: return False print True
Should work like this:
>>> containsNoDivisor(21, []) True >>> containsNoDivisor(21, [2, 4, 5, 6, 8, 9]) True >>> containsNoDivisor(21, [3]) False
findPrimes
def findPrimes(n): '''Computes the list of primes < n. ''' primes = [2] for i in range(3, n): if containsNoDivisor(i, primes): primes.apend(i) return primes
Should work like this:
>>> findPrimes(30) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]