I recent read again the beautiful intro to recursion in the ‘simply scheme’ book (here’s the link to the relevant chapter), where this recursive procedure is introduced (in the scheme language):
(define (downup wd)
(if (= (count wd) 1)
(se wd)
(se wd (downup (bl wd)) wd)))
> (downup 'toe)
(TOE TO T TO TOE)
> (downup 'banana)
(BANANA BANAN BANA BAN BA B BA BAN BANA BANAN BANANA)
I tried to translate that procedure into python, which I use in my day job. Here’s the result:
def recursivefun(word):
if len(word) == 1:
return word
else:
x = []
x.append(word)
x.extend(recursivefun(word[1:]))
x.append(word)
return x
print recursivefun("ciao")
# ==> ['ciao', 'iao', 'ao', 'o', 'ao', 'iao', 'ciao']
So my question is: is there a better way to represent this recursive procedure in python? Or maybe a more ‘elegant’ way?
If you want to closely represent the original recursive Scheme function:
Note that your own function returns a string if the length of the passed in string is 1 and a list otherwise. This could lead to surprising behaviour. Try
for example, which prints
which might be different from what you expected.