Suppose I have a list
.I want to multiply its all elements except with the i'th element.
Example:
- input: [1,2,3,4]
- output: [24,12,8,6]
Here, the output
24 is 2*3*4
12 is 1*3*4
8 is 1*2*4
6 is 1*2*3
Any help would be appreciated
CodePudding user response:
A simple solution using two for loops:
l=[1,2,3,4]
out=[]
for i in range(len(l)):
prod=1
for j in range(len(l)):
if(j!=i): #Iterate through list once more and compare the indices
prod=prod*l[j]
out.append(prod)
print(out)
Output is: [24, 12, 8, 6]
CodePudding user response:
A solution using itertools.combinations
(and reversed to get the right order)
from itertools import combinations
from operator import mul
from functools import reduce
values = [1, 2, 3, 4]
result = [reduce(mul, c) for c in combinations(reversed(values), r=len(values) - 1)]
print(result) # [6, 8, 12, 24]
Or using your logic directly : iterate and for each index don't use the corresponding value
values = [1, 2, 3, 4]
result = []
for i in range(len(values)):
x = 1
for idx, value in enumerate(values):
if i != idx:
x *= value
result.append(x)
print(result) # [24, 12, 8, 6]
CodePudding user response:
You can use numpy
, like below:
import numpy as np
arr = np.array([1,2,3,4])
[np.prod(np.delete(arr, idx)) for idx in range(len(arr))]
# [24, 12, 8, 6]
If you want to not install numpy
you can do like below: ([::-1] reverse liest)
from itertools import combinations
import math
arr = [1, 2, 3, 4]
[math.prod(a) for a in combinations(arr, r=len(arr) - 1)][::-1]
# [24, 12, 8, 6]