python反向列表递归,仅使用

时间:2012-11-20 12:48:39

标签: python list function recursion

我只使用这些函数使用递归来反转列表时遇到问题:

def head(xs):
    return xs[0]

def tail(xs):
    return xs[1:]

def empty(xs):
    return len(xs) == 0

我可以这样做:

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

有没有办法不使用append()??

2 个答案:

答案 0 :(得分:5)

def head(xs):
    return xs[0]

def tail(xs):
    return xs[1:]

def empty(xs):
    return len(xs) == 0

def reverse(xs):
    if empty(xs): return []
    return reverse(tail(xs))+[head(xs)]

xs = range(4)
print(reverse(xs))

产量

[3, 2, 1, 0]

答案 1 :(得分:2)

您可以避免更改列表,而是返回一个新列表:

def p(xs1, xs2):
    if not empty(tail(xs1)):
        xs2 = p(tail(xs1), xs2)
    return xs2 + [head(xs1)]

def p05(xs):
    return p(xs, [])

您可能应该更改head()以返回列表:

def head(xs):
    return xs[:1]

def tail(xs):
    return xs[1:]

并且不需要'空'; []在python上下文中被视为False。然后p()变为:

def p(xs1, xs2):
    if tail(xs1):
        xs2 = p(tail(xs1), xs2)
    return xs2 + head(xs1)

演示:

>>> p(range(5), [])
[4, 3, 2, 1, 0]