A list contains all the ints between 1 and n, but one of them is missing. (The list is of length n-1). What is the missing integer?
Here is one possible solution:
def missing_k(L):
n = len(L) + 1
#Try every k: 1, 2, 3, ..., n, and see which
#k is missing
for k in range(1, n+1):
if k not in L:
return k
#will never get here, since one of the k's will
#not be in L and we'll return it
Let's rewrite this a little bit, imagining that we can't use k not in L
def elem_in_list(elem, L):
'''Return True iff elem is in L'''
for e in L:
if e == elem:
return True
#Tried every element, and didn't find any of them
#in L
return False
def missing_k(L):
n = len(L) + 1
for k in range(1, n+1):
if not elem_in_list(k, L):
return k
Note that we have to look through the list many times (n times, in fact -- we potentially look through the entire list every time we call elem_in_list) in order to solve the problem this way