Skip to main content
 首页 » 编程设计

python之排除迭代地计算列表项的乘积

2024年11月24日8tuyile006

给定一个整数数组,返回一个新数组,使得新数组索引 i 处的每个元素都是原始数组中除了 i 处的元素以外的所有数字的乘积。

例如,如果我们的输入是[1, 2, 3, 4, 5],则预期的输出将是[120, 60, 40, 30, 24]。如果我们的输入是 [3, 2, 1],则预期输出将是 [2, 3, 6]。

这是我想出来的

python

def get_nth_fib(n): 
    if n is 0: 
        return 0 
    product = 1 
    for i in n: 
        product *= n 
    for i in range(len(n)): 
        n[i] = product / n[i] 
    return n[i] 
 
 
print(get_nth_fib([1, 2, 3, 4, 5])) 
 
line 11 
line 6, in getNthFib 
     
TypeError: can't multiply sequence by non-int of type 'list' 

请您参考如下方法:

通过简单的算术排除:

from functools import reduce 
from operator import mul 
 
lst = [1, 2, 3, 4, 5] 
prod = reduce(mul, lst)    # total product 
result = [prod // i for i in lst] 
 
print(result)    # [120, 60, 40, 30, 24]