简体   繁体   中英

Compute product of list items iteratively with exclusion

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5] , the expected output would be [120, 60, 40, 30, 24] . If our input was [3, 2, 1] , the expected output would be [2, 3, 6] .

This is what I have come up with

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'

With simple arithmetic exclusion :

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]

Just some changes: product *= i and return n .Try this out:

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]))

There may be a challenging condition that this problem is solved without using division. Here's my solution on python for that requirement:

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

The function product() was declared in advance as:

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

Method 1:

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)

Method 2:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM