Skip to content

Instantly share code, notes, and snippets.

@vrthra
Last active April 17, 2022 20:32
Show Gist options
  • Save vrthra/61b30c9bfdfa6fb9f8efbd56b8239f7b to your computer and use it in GitHub Desktop.
Save vrthra/61b30c9bfdfa6fb9f8efbd56b8239f7b to your computer and use it in GitHub Desktop.
Getting around Python recursion limit
# https://speakerdeck.com/dabeaz/generators-the-final-frontier?slide=163
def cps(gen):
stack = [gen]
ret = None
while stack:
try:
value, ret = ret, None
res = stack[-1].send(value)
stack.append(res)
except StopIteration as e:
stack.pop()
ret = e.value
return ret
def factorial(n):
if n <= 1:
return 1
value = factorial(n - 1)
return value * n
#print(factorial(1000))
def factorial(n):
if n <= 1:
return 1
value = yield factorial(n - 1)
return value * n
print(cps(factorial(10000)))
def countdown(start):
print start
if start == 0:
return 0
else:
return countdown(start - 1)
print(cps(countdown(1000)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment