def returned(n): """Generate a random walk and return True if the walker has returned to the origin after taking `n` steps. """ ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk() >> drop(1) >> takei(xrange(n-1)): if pos == Origin: return True return False
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of memory! Thus, try this interactively only. """ walk = randwalk() >> drop(1) >> takewhile(lambda v: v != Origin) >> list return len(walk)