Hacker News new | ask | show | jobs
by BobKabob 5572 days ago
Here's a solution in Python, using pretty much the same logic as the top vote-getter on Stack Overflow:

    def f(a):
        print a
        print a+1
        {999: int}.get(a,f)(a+2)

    f(1)
Note, I had to count by twos, because when I counted by ones, I got a "maximum recursion limit exceeded" error.

Basically, the concept is to call f recursively, until you get to 999 (and had printed 999 and 1000), at which time you call some non-recursive function (I call "int").

At 999, the inner-called f function terminates, leading to the unwinding of the stack (each previous f function terminating), and then the program ends.

This statement is the hard one to understand:

        {999: int}.get(a,f)(a+2)
Basically, it's saying "Look up 'a' in this hard-coded dictionary that only has one value in it - for 999. If 'a' isn't found (as it won't be most of the time), set the look-up value to the function called 'f'. Otherwise, set the look-up value to the function called 'int'. In either case, call that looked-up value, passing the parameter of a+2."