Skip to content

Instantly share code, notes, and snippets.

@shivamMg
Last active April 20, 2018 11:49
Show Gist options
  • Select an option

  • Save shivamMg/7d5b10a8f0948a9ec767135be1eee40d to your computer and use it in GitHub Desktop.

Select an option

Save shivamMg/7d5b10a8f0948a9ec767135be1eee40d to your computer and use it in GitHub Desktop.
Arithmetic Progression with a Closure, and a Generator
def arith(a: 'initial term', d: 'common difference'):
"""Returns initial and subsequent arithmetic progression terms"""
current = a - d
def _():
nonlocal current
current += d
return current
return _
def arith_gen(a, d):
"""Same function as above except it uses generators"""
current = a
while True:
yield current
current += d
if __name__ == '__main__':
a = arith(1, 2)
print(a())
print(a())
print(a())
a = arith_gen(1, 2)
print(next(a))
print(next(a))
print(next(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment