Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Poked around on the google[0]:

  def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return b
No itertools, not overly complex, no tail recursion.

If you were careful of the scoping rules something like foo(get_next(i) for i in whatever()) could be made to work without too much trouble (also without itertools) if you needed a sequence. Probably just throw a lambda in there instead of get_next and python would be happy, too lazy to work it out.

[0]http://www.koderdojo.com/blog/python-fibonacci-number-genera...

--edit--

Actually, I think this function gives the wrong result for 0 and maybe 1, just copypasta'd the code so blame them...



I think this is the correct way to do this in a Python codebase where procedural programming is the dominant paradigm, but that's not really what my previous post is about.

EDIT: Also c'mon man. This is not a problem that you need to Google. :P




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: