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

时间:2019-07-14 19:41:19

标签: python

给出一个整数数组,返回一个新数组,使得新数组索引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'

4 个答案:

答案 0 :(得分:1)

使用简单的算术排除

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]

答案 1 :(得分:0)

只需进行一些更改:product *= ireturn n。尝试一下:

def get_nth_fib(n):
    if n is 0:
        return 0
    product = 1
    for i in n:
        product *= i
    for i in range(len(n)):
        n[i] = product / n[i]
    return n


print(get_nth_fib([1, 2, 3, 4, 5]))

答案 2 :(得分:0)

可能存在一个具有挑战性的条件,即不使用除法即可解决此问题。 这是我针对python的解决方案:

def problem(old_array):
  array = old_array.copy()
  new_array = []
  for num in old_array:
    temp_array = array.copy()
    i = array.index(num)
    temp_array.remove(temp_array[i])
    new_element = product(temp_array)
    new_array.append(new_element)
  return new_array

函数product()预先声明为:

def product(list):
  return numpy.prod(list)

答案 3 :(得分:0)

方法一:

list = [1, 2, 3, 4, 5]
result = []
temp = 1
for x in range(len(list)):
    
    for y in range(len(list)):
        if (y != x ):
            temp = temp * list[y]
    
    result.append(temp)
    temp = 1
print("Method 1:  ",result)

方法二:

import numpy
#Method 2
result = []
list = [1, 2, 3, 4, 5]
for i in range(len(list)):
    tempList = list.copy()
    tempList.pop(i)
    multiplied_List = numpy.prod(tempList)
    result.append(multiplied_List)
print("Method 2:  ",result)