A ListComp that maintains its own state

Michael Spencer mahs at telcopartners.com
Wed Feb 9 13:10:45 EST 2005


Bernhard Herzog wrote:
> Michael Spencer <mahs at telcopartners.com> writes:
> 
> 
>>So, here's factorial in one line:
>># state refers to list of state history - it is initialized to [1]
>># on any iteration, the previous state is in state[-1]
>># the expression also uses the trick of list.append() => None
>># to both update the state, and return the last state
>>
>> >>> [state.append(state[-1] * symbol) or state[-1]
>>...         for symbol, state in it.izip(range(1,10),it.repeat([1]))
>>...             ]
>>[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>> >>>
> 
> 
> There's no need for repeat:
> 
> 
>>>>[state.append(state[-1] * symbol) or state[-1] 
> 
>         for state in [[1]]
>         for symbol in range(1, 10)]
> [1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
> 
> 
> While we're at it, a while back I posted a list comprehension that
> implements a 'recursive' flatten:
> 
> http://groups.google.de/groups?selm=s9zy8eyzcnl.fsf%40salmakis.intevation.de
> 
> 
>    Bernhard
> 
Much better - that also cleanly extends to any number of initializers.  I also 
like the approach you take in flatten (and as suggested by Carl Banks) of 
putting the update mechanism in the if clause

So that gives:

def factorial(n):
     return [state[-1]
             for state in [[1]]
                 for count in xrange(1,n+1)
                     if state.append(state[-1] * count) or True
                 ]

Probably of limited practical value, but fun to explore the language.


Thanks
Michael





More information about the Python-list mailing list