A ListComp that maintains its own state (Was: Re: turing machine in an LC)

Michael Spencer mahs at telcopartners.com
Tue Feb 8 17:00:25 EST 2005


> Jeremy Bowers <jerf at jerf.org> writes:
> 
> 
>>On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote:
>>
>>>Nick Vargish <nav+posts at bandersnatch.org> writes:
>>>
>>>>"Xah Lee" <xah at xahlee.org> writes:
>>>>
>>>>>is it possible to write python code without any indentation?
>>>>
>>>>Not if Turing-completeness is something you desire.
>>>
Bernhard Herzog wrote:
....
a Turing Machine in one line plus assignments - nice!  Turns out that pypy is more
verbose than strictly necessary ;-)
...


BTW, I realized that it is indeed possible for a LC to maintain its own state 
without being passed an external mutable.  The trick is to use itertools.repeat 
to return the same mutable object on each iteration.

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]
 >>>

Now, who was claiming that 'reduce' was opaque?

Michael ;-)




More information about the Python-list mailing list