Home > Enterprise >  Taking all elements except the current element
Taking all elements except the current element

Time:04-15

I want to take all the elements in the list except the current element. Here is the List:

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

I tried using list comprehension:

[(nums[:x:],nums[x 1:]) for x in range(len(nums)) ]

This is the output I am getting:

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

I am getting two blank lists one in the beginning and one at the end which is correct. I want to know if there is a way where I can edit these 2 blank lists to [1] by putting any validation?

In essence I need to calculate the product of all the numbers except the current number and I am not allowed to use division.

Also, there is a time constraint that I cannot use nested/multiple for loops as test cases will fail on exceeding time limit

CodePudding user response:

Based on your final goal, it seems like you don't need two separate lists for before/after the current number. Instead, concatenate them and apply prod. That way you don't even need to worry about the empty list issue.

from math import prod

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

prods = [prod(nums[:i]   nums[i 1:]) for i in range(len(nums))]
print(prods) # [1440, 1440, 480, 288, 720, 480, 360, 360]

CodePudding user response:

Not very pretty, but this works:

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

n = [(nums[:x:],nums[x 1:]) if x!=0 and x!=len(nums)-1 else ((nums[:x:],[1]) if x==len(nums)-1 else ([1],nums[x 1:])) for x in range(len(nums)) ]

print(n)

Output:

[([1], [1, 3, 5, 2, 3, 4, 4]), ([1], [3, 5, 2, 3, 4, 4]), ([1, 1], [5, 2, 3, 4, 4]), ([1, 1, 3], [2, 3, 4, 4]), ([1, 1, 3, 5], [3, 4, 4]), ([1, 1, 3, 5, 2], [4, 4]), ([1, 1, 3, 5, 2, 3], [4]), ([1, 1, 3, 5, 2, 3, 4], [1])]
  • Related