recursion depth problem

Alex Martelli aleax at mac.com
Mon Apr 23 04:23:05 CEST 2007


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.


Alex



More information about the Python-list mailing list