How to find out the minimum no. of elements in a List which has sum equals to given value, in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to find out the minimum no. of elements in a List which has sum equals to given value, in Python

List = [2,3,5] (sequence of prime numbers list. len(list) = n = 3) sum = 11 output = [5,3,3] (minimum no.of elements which gives the sum of 11 When i'm executing the following i can able to get the output of unique elements but i want to add the elements repeatedly if required like(5+3+3). Can someone help to me to find out this? import itertools total = 9 array = [2,3,5] for i in range(1, len(array)+1): for w in itertools.combinations(array, i): if sum(w) == total: print (list(w))

20th May 2020, 11:32 AM
Somasundaram K
Somasundaram K - avatar
4 Answers
+ 3
You should use combinations_with_replacement instead: import itertools total = 9 array = [2,3,5] for i in range(1, len(array)+1): for w in itertools.combinations_with_replacement(array, i): if sum(w) == total: print (list(w)) >>> [2, 2, 5] [3, 3, 3]
20th May 2020, 12:33 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 1
You only allowed the combinations to be of "i" elements. Since "i" assumes values: 0 and 1 (in the for loop), you only receive the result for such, which is empty, of course. Try iterating from 1 to the number which is the value of the "total" divided by the smallest element of the array (then +1) to guarantee the result, if it is possible at all. Oh, and don't use 0 as the array element, of course ;)
20th May 2020, 3:30 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
0
I tried this code(plz don't mind the syntax) t=2,3,4 n=11 y=[ ] for a in t: for b in t: for c in t: If (a+b+c)==n: y=y+[[a,b,c]] Print(y) I got three outputs 3,3,5 3,5,3 5,3,3 This is a very bad way of solving this but.... If you can make a function which can generate for loops like the ones above then this will work
20th May 2020, 1:11 PM
Yash Jain
Yash Jain - avatar
0
@ Kuba SiekierzyƄski and @Yash Jain Thank you. but still i have small issue . when I'm trying to run this input is not running since its not a combination import itertools total = 4 array = [2] for i in range(len(array)+1): for w in itertools.combinations_with_replacement(array, i): if sum(w) == total: print ((w)) I want to get an output of [2,2] #2+2 = 4
20th May 2020, 2:05 PM
Somasundaram K
Somasundaram K - avatar