0

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:

  • a-f are unique integers [1,6]

  • I'm using python and trying to solve without using built-in functions or libraries

  • Use 6 nested for-loops to enumerate all ways of setting each of a, b, c, d, e, and f to the values 1-6 (part I'm having an issue understanding how to organize)

  • Apparently there is only one permutation that will solve this particular equation

geominded
  • 201
  • 2
  • 10

2 Answers2

1

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)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Ah thanks! I'm not interested in just calling a permutations function, but the documentation on the function is useful! So the examples still use built-in python functions like product, but that's a start. – geominded Apr 17 '17 at 20:55
1

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}
Roland Smith
  • 42,427
  • 3
  • 64
  • 94