Seeking generalized way to solve equation using all possible combinations of values of two lists in python

Viewed 80

i want to see which combinations of the product of each of these lists solves an equation, "j=k-l+m"

stake=[0,2,5,10]
odds=[1,2,5,10]

The only way i can think of so far is as follows. I create a list of tuples using product function like so

from itertools import product

stake_odds=(list(product(stake,odds)))
print(stake_odds)
>>>[(0, 1), (0, 2), (0, 5), (0, 10), (2, 1), (2, 2), (2, 5), (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)]

i then create a further list of the combinations of tuples of length the number of variables in my equation:

stake_odds2=(list(product(stake_odds, repeat=3)))

then I do the following

pos_combos=[]
for i in stake_odds2:
    x,y,z=i
    a,b=x
    c,d=y
    e,f=z
    k=a*b
    l=c*d
    m=e*f
    j=k-l+m
    if j > 0:
        pos_combos.append(i)

printing pos_combos returns what i want. My issue is however is that if i want to expand the equation or the two lists then it obviously becomes a nightmare to unpack the tuples and label everything, even the above is giving me a headache looking at it.

Is there any slicker way of doing this? maybe any simulation packages i should be aware of?

Thanks in advance

1 Answers

There's no need to unpack all of those variables, just take the product of the tuples then do the final math.

from itertools import product
import numpy as np
stake=[0,2,5,10]
odds=[1,2,5,10]
stake_odds=(list(product(stake,odds)))
stake_odds2=(list(product(stake_odds, repeat=3)))

for i in stake_odds2:
    t = [np.prod(x) for x in i]
    if t[0]-t[1]+t[2]>0:
        pos_combos.append(i)
Related