recursion depth problem
Steven Bethard
steven.bethard at gmail.com
Sun Apr 22 16:06:19 EDT 2007
proctor wrote:
> On Apr 22, 1:24 pm, Michael Bentley <mich... at jedimindworks.com> wrote:
>> On Apr 22, 2007, at 1:49 PM, proctor wrote:
>>
>>
>>
>>> i have a small function which mimics binary counting. it runs fine as
>>> long as the input is not too long, but if i give it input longer than
>>> 8 characters it gives
>>> RuntimeError: maximum recursion depth exceeded in cmp
>>> i'm not too sure what i am doing improperly. is there really a lot of
>>> recursion in this code?
>>> ==================
>>> 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]))
>>> ==================
>> Yes. There really is *that* much recursion in that code. 502 levels
>> with input length of 8 characters, 1013 with 9 characters, 2035 with
>> 10 characters... There's a pattern there ;-)
>
> ok, thanks michael!
>
> is there a way to avoid it here? how could i write this better, (if
> at all)?
Google for permutation-like recipies:
http://www.google.com/search?q=Python+permutations
Use the code from the first hit::
>>> for x in xselections('01', 8):
... print ''.join(x)
...
00000000
00000001
00000010
...
11111101
11111110
11111111
Explaining to your teacher why your code uses generators when you
haven't been taught them yet is left as an exercise to the reader. ;-)
STeVe
More information about the Python-list
mailing list