I have a list of integers and I would like to print all integers whose sum is less than than or equal to a variable. My sum is 38 below, how do I randomly return the values in the list below where my sum is less than or equal to 15? I have tried to adapt the function below, but it doesn't work.
j=[4,5,6,7,1,3,7,5]
x = 15
jSum = sum(j)
def decomposition(i):
while i <= x:
n = random.randint(j, i)
yield n
i -= n
print i
decomposition(jSum)
Let's create a list
of possible lists
with sums
< x
. This can be done with two nested for-loops
and itertools.combinations
:
ops=[list(c) for l in range(1,len(j)) for c in itertools.combinations(j,l) if sum(c) < x]
then just randomly
select one with random.choice
:
random.choice(ops)
And when I ran this with j = [4,5,6,7,1,3,7,5]
and x = 15
the random output I got was:
[6, 1, 3]
Which works! ( sum
is < 15
and all elements are in j
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.