find all multiplicands and multipliers for a number

Chris Kaynor ckaynor at zindagigames.com
Wed Apr 15 18:46:15 CEST 2015


On Wed, Apr 15, 2015 at 9:21 AM, Paul Rubin <no.email at nospam.invalid> wrote:
> Ian Kelly <ian.g.kelly at gmail.com> writes:
>> Nope. You do end up with a lot of nested filter objects, but there's
>> no recursion in the Python code, which means that you're not piling up
>> frame objects, and you'll never hit the interpreter's recursion limit.
>
> I think you do get frame objects.  A quick experiment:
>
>  def d(fuel):
>         f = lambda x:x
>         for i in range(fuel): f = lambda x,g=f: 1+g(x)
>         return f
>
>     >>> d(3)
>     <function <lambda> at 0x1a3b9b0>
>     >>> d(100)(0)
>     100
>     >>> d(1000)(0)
>
>     Traceback (most recent call last):
>       File "<pyshell#24>", line 1, in <module>
>         d(1000)(0)
>       File "<pyshell#20>", line 3, in <lambda>
>         for i in range(fuel): f = lambda x,g=f: 1+g(x)
>       File "<pyshell#20>", line 3, in <lambda>
>       [ 1000's of lines snipped ]
>     RuntimeError: maximum recursion depth exceeded
>     >>>

That code is substantially different that the code that Steven
D'Aprano posted: Steven's uses filter to call the lambdas, while your
calls the lambdas from another lambda. Basically, yours has direct
recursion in the Python code, while Steven's does not. The only
recursion in Steven's code is inside of the filter built-in function,
very nicely masked :).

Running Steven's code for a while, on a 32-bit install of Python 3.4.2
on Win64, printing the results, eventually produces:
[A whole pile of primes snipped]
784489
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in turner
  File "<stdin>", line 6, in <lambda>
MemoryError: Stack overflow



More information about the Python-list mailing list