列表的递归除法

Recursive division over a list

我希望像这样递归地划分列表的每个元素。

a_list = [1, 2, 3, 4, 5] 所以 returns 将是 1/(2/(3/(4/5)))

def c(y):

    if not y:
        return 1  # division by 1 don't matter

    return c(y[1:])[0] / c(y[2:])[1]  # Not allowed

你的修复了,一些主要是 non-recursive 替代品(@9769953 修复了,有些是我修复的):

for y in [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6]:
    print(y)

    def c(y):
        if not y:
            return 1
        return y[0] / c(y[1:])
    print(c(y))

    from functools import reduce
    print(reduce(lambda a, b: b / a, reversed(y)))

    from math import prod
    print(prod(y[::2]) / prod(y[1::2]))

    z = 1
    for x in reversed(y):
        z = x / z
    print(z)

    def d(y):
        y = iter(y)
        try:
            return next(y) / d(y)
        except StopIteration:
            return 1
    print(d(y))

    print()

输出显示两个测试用例和五个解决方案的结果 (Try it online!):

[1, 2, 3, 4, 5]
1.875
1.875
1.875
1.875
1.875

[1, 2, 3, 4, 5, 6]
0.3125
0.3125
0.3125
0.3125
0.3125

您可以对索引使用简单的递归。例如:

a_list = [i + 1 for i in range(6)]


def divide(index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(index + 1)


print(divide()) # 0.3125

或者,等效的实现,但将列表作为参数传递:

def divide(a_list: list, index: int = 0) -> float:
    if index == len(a_list):
        return 1
    return a_list[index] / divide(a_list, index + 1)

a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125

或者,使用您原来的方法:

def divide(a_list: list) -> float:
    if not a_list:
        return 1
    n, *d = a_list
    return n / divide(d)


a_list = [i + 1 for i in range(6)]
print(divide(a_list)) # 0.3125

递归地,你可以将第一个元素除以与其余元素递归的结果:

def recDiv(a):
    return a[0] / recDiv(a[1:]) if a else 1

a_list = [1, 2, 3, 4, 5]

print(recDiv(a_list)) # 1.875

或者,您可以使用数学中的 prod() 函数,并根据项目处于偶数或奇数位置应用 1 或 -1 的幂。

a_list = [1, 2, 3, 4, 5]

from math import prod

result = prod(n**[1,-1][i&1] for i,n in enumerate(a_list))

print(result) # 1.875

这将转化为这样的常规循环:

result = 1
for i,n in enumerate(a_list):
    result *= n ** [1,-1][i&1]  # result *= 1/n if i%2 else n
    
print(result) # 1.875