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

From: Michael Spencer (mahs_at_telcopartners.com)
Date: 02/08/05


To: python-list@python.org
Date: Tue, 08 Feb 2005 14:00:25 -0800


> Jeremy Bowers <jerf@jerf.org> writes:
>
>
>>On Tue, 08 Feb 2005 17:36:19 +0100, Bernhard Herzog wrote:
>>
>>>Nick Vargish <nav+posts@bandersnatch.org> writes:
>>>
>>>>"Xah Lee" <xah@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 ;-)



Relevant Pages

  • Re: Word 2003 table reformats when pasted to Word 2007
    ... Thanks Pamilia you're recommendation did the trick. ... BTW: the someone who changed the settings in Word Options is me. ...
    (microsoft.public.word.tables)
  • Re: Disable Simple File Sharing in Home Edition
    ... :piece of code in XP Home is reintroducing any of these ... :instabilities, which BTW were all resultant from a change ... :I'm using this trick since I've found it without any problem. ...
    (microsoft.public.windowsxp.security_admin)
  • Re: installing .debs from hdd
    ... Maintainers Guide shows nothing applicable. ... That did the trick. ... BTW, where in the docs does it mention this ... If you think you're getting free lunch, ...
    (Debian-User)
  • Re: bignum 0.22
    ... gamo wrote: ... BTW, if you make factrecursive and use the Memoize module, you can ... This trick really really improve speed. ...
    (comp.lang.perl.modules)
  • Re: Monte Carlo - saving data
    ... Your trick of saving variables worked for me. ... variable for each iteration if it is a Character?? ... I've been working my way up to a Monte Carlo simulation ... output the variable "altitude" for each run but it's ...
    (comp.soft-sys.matlab)