How to get sum of products of all combinations in an array in Python? [closed]
2024/11/15 20:01:19
I'm using Python and
I'm given an array like a = [1, 2, 3, 4]
and I want to find sum of all possible combination multiplications like:
For combinations of 1: 1 + 2 + 3 + 4
For combinations of 2:1*2 + 2*3 + 3*4 + 4*1.
For combination of 3: 1*2*3 + 1*3*4 + 2*3*4
For combinations of 4: 1*2*3*4
And finally sum of all these sums is my answer. I'm using numpy.prod() and numpy.sum(). But it's still too slow. Is there some better algorithm to find the sum quickly?
Answer
You can do with numpy and itertools:
from numpy import linspace, prod
from itertools import combinationsarr = np.array([1,2,3,4])[sum([prod(x) for x in combinations(arr,int(i))]) for i in linspace(1,len(arr), len(arr))]
[10, 35, 50, 24]
When using the function entry of Tkinter, you can write a string value and do things with it; but Im actually working with formulas. The idea is fairly simple: to put a bunch of boxes to fill with numb…
Im not getting how to proceed with this problem in lists,can any one help me out?
Thanks in advance.input is :l = [(1,2),(3,4),(5,6)]output is:[(1,3,5),(2,4,6)]
I have a question on how to add entries from 100 files (each file contains two columns) and then writing them to a new file(which will also contain two columns)?
I have 2 lists: list1 and list2
list1 is a list in list and contains various strings
list2 is also a list in list and consists of different integer values
the dimensions of both lists is the same
how d…
import random
number = random.randint(1, 10)player_name = input("Hello, Whats your name?")
number_of_guesses = 0
print(okay! + player_name+ I am Guessing a number between 1 and 10:)while nu…
I have two lists. One is simply a list of idsids = [123, 124, 127, 316, 463]and the other is a list of tuples of ids and namescombined = [(123, "Brian"), (124,"Eric"), (222,"Ja…
I was trying to get a series of sum from 1 to n, 2 to n, ..., and nFor example, if n=5, then the result should be
15
14
12
9
5Please comment for the code below. I cant figure out whats wrong.n=int(inpu…
Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…
This question already has answers here:How do I create variable variables?(18 answers)Closed 6 years ago.I am having a function in pythondef func(dataFrame,country,sex):varible_name=dataFrame[(dataFra…
This question already has answers here:Why is the order in dictionaries and sets arbitrary?(5 answers)Closed 8 years ago.Just curious more than anything else, but why isnt a dictionary such as the one…