2

Lets say I have such naive implementation of program which recursively adds ones to a given number.

s=lambda n, i: i>0 and s(n+1, i-1) or n

However it won't add more than recursion limit. Such call with default recursion limit would fail:

s(0, 1000000)

Is there a way, how to solve it with recursion but without limit change?

I thought about the way where I call this function 900 times, if number still greater than 0, I add those 900 to some number, reduce added number by 900 and call this function once more. But can't handle how to write such lambdas.

Viacheslav Kondratiuk
  • 8,493
  • 9
  • 49
  • 81

2 Answers2

3

Try making it logn:

s=lambda n,lim=1000000: 1 if lim==1 else n+s(0,lim//2)+s(0,lim-(lim//2))

print(s(0))

Or, without vowels other than 'a':

t=lambda n,l: 1
v=lambda n,l: n+s(0,l//2)+s(0,l-(l//2))
s=lambda n,l=1000000: (t,v)[l!=1](n,l)
aghast
  • 14,785
  • 3
  • 24
  • 56
  • 1
    Note that in the question's comments it was specified that the only permitted vowel is "a," which would rule out `if` and `else` (`lim` could be renamed). I would've suggested `lim==1 or n+s(...`, but `or` isn't allowed either. – TigerhawkT3 May 12 '16 at 20:55
-1

Use divide and conquer:

add = lambda n,l: l > 1 and add(n,l//2) + add(n+l//2, l-l//2) or n

PS: this solution is released under the license, that it is not allowed to use it in any competition or challenge. Any derived work must be released under the same license. For any other usage, its free without the need to mention the author.

Daniel
  • 42,087
  • 4
  • 55
  • 81