简体   繁体   中英

Using the enumerate function, is there a way to reference the index without also referencing the element?

I need to write a function that receives an array of integers and returns an array consisting of the product of all numbers in the array except the number at that index

For example, given:

[3, 7, 3, 4]

The function should return:

[84, 36, 84, 63]

By calculating:

[7*3*4, 3*3*4, 3*7*4, 3*7*3]

The function that I've written will work if the array contains no duplicates, but I can't seem to figure out how to reference skipping the index without also skipping any number in the array with the same value as the index.

def product_of_all_other_numbers(arr):
     product_array = []
     for idx, val in enumerate(arr):
         running_count = 1
         for n in arr:
             if n != arr[idx]:
                 running_count *= n
         product_array.append(running_count)
     return product_array

Is this possible with enumerate or should I start exploring a different route?

I can't seem to figure out how to reference skipping the index without also skipping any number in the array with the same value as the index.

There's no need to compare the values at that index , you only care about the index . So your inner loop could be like this:

def product_of_all_other_numbers(arr):
     product_array = []
     for idx, val in enumerate(arr):
         running_count = 1
         for i, n in enumerate(arr):
             if i != idx:
                 running_count *= n
         product_array.append(running_count)
     return product_array

Note, there are more efficient solutions to this problem, but this addresses your current issue.

You could use numpy prod method and list slicing

In [91]: import math
In [92]: def product_of_all_other_numbers(lst):
    ...:     data = []
    ...:     for i in range(len(lst)):
    ...:         data.append(math.prod(lst[:i] + lst[i+1:]))
    ...:     return data
    ...:

In [93]: product_of_all_other_numbers([3, 7, 3, 4])
Out[93]: [84, 36, 84, 63]

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