import time def make_dice(sides = 6, seed = None): """A new 'sides'-sided die that yields numbers between 1 and 'sides' when called. 'seed' controls the sequence of values. If it is defaulted, the system chooses a non-deterministic value.""" if seed == None: seed = int(time.time() * 100000) a, c, m = 25214903917, 11, 2**48 # From Java def die(): nonlocal seed seed = (a*seed + c) % m return seed % sides + 1 return die def frequencies(L): """A dictionary giving, for each w in L, the number of times w appears in L. >>> frequencies(['the', 'name', 'of', 'the', 'name', 'of', 'the', ... 'song']) {'of': 2, 'the': 3, 'name': 2, 'song': 1} """ return { L[i-1]: L[i] for i in range(1, len(L)) } # Or, the long way: def frequencies2(L): """A dictionary giving, for each w in L, the number of times w appears in L. >>> frequencies(['the', 'name', 'of', 'the', 'name', 'of', 'the', ... 'song']) {'of': 2, 'the': 3, 'name': 2, 'song': 1} """ result = {} for i in range(1, len(L)): result[L[i-1]] = L[i] return result def is_duplicate(L): """True iff L contains a duplicated item.""" items = {} for x in L: if x in items: return True items[x] = True # Or any value return False def common_keys(D0, D1): """Return dictionary containing the keys common to D0 and D1.""" result = {} for x in D0: if x in D1: result[x] = True return result def make_counter(): """Returns a function that returns the next higher integer each time it is called, starting with 0. >>> c = make_counter() >>> c() 0 >>> c() 1 >>> c() 2 """ count = 0 def counter(): nonlocal count count += 1 return count - 1 return counter def make_account(balance): """A new bank account with initial balance `balance`. If acc is an account returned by make_account, then acc('balance') returns the current balance. acc('deposit', d) deposits d cents into the account acc('withdraw', w) withdraws w cents from the account, if possible. 'deposit' and 'withdraw' return acc itself. >>> a = make_account(100) >>> a('balance') 100 >>> a('withdraw', 10) >>> a('balance') 90 """ def acc(op, *opnds): nonlocal balance if op == 'balance' and len(opnds) == 0: return balance elif op == 'deposit' and len(opnds) == 1 and opnds[0] > 0: balance += opnds[0] elif op == 'withdraw' and len(opnds) == 1 \ and 0 <= opnds[0] <= balance: balance -= opnds[0] else: raise ValueError() return acc