[Tutor] Re: a recursion opportunity
Christopher Smith
csmith@blakeschool.org
Fri, 08 Feb 2002 17:25:26 -0600
glingl@aon.at writes:
>
>To break the silence, this is my solution:
>
>
>def gray(l):
> if l:
> return ['0'+l[0]] + gray(l[1:]) + ['1'+l[0]]
> else:
> return []
>
>def graycode(n):
> if n:
> return gray(graycode(n-1))
> else:
> return ['']
>
>I'm interested in yours. Can it be done in ONE SINGLE recursive function?
>Gregor
After watching the tutor list discuss these this summer and after breaking
my mind on the permutations problem via recursion I think I'm starting to
get it: this was what I did:
def graycode(n):
if n==0:
return ['']
else:
l=[]
g=graycode(n-1)
for gi in g:
l.append('0'+gi)
g.reverse()
for gi in g:
l.append('1'+gi)
return l
for i in range(4):
print graycode(i)
I especially like it because for the first time it seemed like I could
translate teh difinition into a code in a natural way. That's why I
thought it would make a good "early experience" recursion exercise.
/c
>