I’m having problems reversing a list using recursion using only these functions:
def head(xs):
return xs[0]
def tail(xs):
return xs[1:]
def empty(xs):
return len(xs) == 0
I can do this:
def p(xs1, xs2):
if not empty(tail(xs1)):
p(tail(xs1), xs2)
xs2.append(head(xs1))
def p05(xs):
s = []
p(xs, s)
return s
Is there a way to do it without using append()??
You could avoid changing the list in place and instead return a new list:
You should probably change
head()to return a list as well:and ’empty’ is not needed;
[]is consideredFalsein a python context. Thenp()becomes:Demonstration: