recursion depth problem
Steven Bethard
steven.bethard at gmail.com
Sun Apr 22 23:22:33 EDT 2007
Alex Martelli wrote:
> Steven Bethard <steven.bethard at gmail.com> wrote:
> ...
>>>>>>> import sys
>>>>>>> def ch4(item, n=0):
>>>>>>> if n < len(item):
>>>>>>> if item[n] == '0':
>>>>>>> item[n] = '1'
>>>>>>> print ''.join(item)
>>>>>>> ch4(item)
>>>>>>> elif item[n] == '1':
>>>>>>> item[n] = '0'
>>>>>>> ch4(item, n+1)
>>>>>>> ch4(list(sys.argv[1]))
> ...
>>> for interest sake: is my method unredeemable?
>> Let's just say that I don't currently see an obvious way of redeeming
>> it. ;-)
>
> Change the outer if into a while, and the recursive calls into proper
> assignments to n. They're both tail-recursive calls, so this won't
> change the semantics, as it happens.
Thanks!
>>> def f(chars):
... n = 0
... while n < len(chars):
... if chars[n] == '0':
... chars[n] = '1'
... n = 0
... print ''.join(chars)
... elif chars[n] == '1':
... chars[n] = '0'
... n += 1
...
>>> f(list('00000000'))
10000000
01000000
11000000
...
10111111
01111111
11111111
Looks good.
STeVe
More information about the Python-list
mailing list