geominded
geominded

Reputation: 207

Solving for variables if you have the equation and variables using Python

If I have an equation, (a + (b - c) d - e) f = 75, how can I iterate through changing my variables a thru f? If a thru f are unique numbers [1,6], then there would be 6! ways of placing the numbers, right? So I imagine I have to increment through my variables somehow.

Assumptions/Limitations:

Upvotes: 0

Views: 379

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

This seems like a good occasion to use sets:

In [17]: set1 = set([1,2,3,4,5,6])

In [18]: for a in set1:
    ...:     for b in set1 - set([a]):
    ...:         for c in set1 - set([a,b]):
    ...:             for d in set1 - set([a,b,c]):
    ...:                 for e in set1 - set([a,b,c,d]):
    ...:                     for f in set1 - set([a,b,c,d,e]):
    ...:                         if (a + (b - c)*d - e)*f == 75:
    ...:                             print('found:', a, b, c, d, e, f)
    ...:                             break
    ...:                         
found: 4 6 2 3 1 5

In [19]: (4+(6-2)*3-1)*5
Out[19]: 75

By using the difference between sets, you make sure that you don't use the same value twice. For example:

In [20]: set([1,2,3,4,5,6]) - set([1,5])
Out[20]: {2, 3, 4, 6}

Upvotes: 1

MSeifert
MSeifert

Reputation: 152587

You can use itertools.permutations (the documentation contains a code sample if you don't want to use it directly):

>>> def func(a, b, c, d, e, f):
...     return (a + (b - c) * d - e) * f == 75

>>> from itertools import permutations

>>> next(filter(lambda x: func(*x), permutations(range(1, 7), 6)))
(4, 6, 2, 3, 1, 5)

Upvotes: 1

Related Questions