Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Taking all elements except the current element

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[([], [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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading