Note that there are some explanatory texts on larger screens.

plurals
  1. POFind equivalent results under distributive and commutative laws
    text
    copied!<p>I have a script that loops over 5 vectors of numbers and mix them with all the four operations searching for a combination that give a certain target number as a result.</p> <p>The script prints an output like:</p> <pre><code>312 / 130 x 350 - 122 + 282 = 1000.0 312 / 130 x 350 + 282 - 122 = 1000.0 312 - 282 x 372 / 15 + 256 = 1000.0 142 + 350 - 372 x 125 / 15 = 1000.0 142 + 350 - 372 / 15 x 125 = 1000.0 350 / 130 x 312 + 282 - 122 = 1000.0 350 + 142 - 372 x 125 / 15 = 1000.0 </code></pre> <p>Each line is formatted from a list of the numbers and a list of the operations.</p> <p>What I'd like to do, is to <strong>remove the equivalent results</strong>, i.e. having an output like:</p> <pre><code>312 / 130 x 350 - 122 + 282 = 1000.0 312 - 282 x 372 / 15 + 256 = 1000.0 142 + 350 - 372 x 125 / 15 = 1000.0 </code></pre> <p>As a solution, at first, I thought about "remembering" the numbers that already gave 1000 and skip those, but then I realized it might shadow new results, so I don't know what to do.</p> <p>How can I find the equivalent results under distributive and commutative laws?</p> <p><strong>Note:</strong> In the presented output the parentheses are NOT shown, but the order is reduce-like, meaning that, for example:</p> <pre><code>142 + 350 - 372 x 125 / 15 = 1000.0 </code></pre> <p>is calculated like:</p> <pre><code>(((142 + 350) - 372) x 125) / 15 = 1000.0 </code></pre> <hr> <p>This is the code I have so far:</p> <pre><code>import operator from itertools import permutations, product, count from functools import reduce vectors = [[87, 125, 209, 312], [29, 122, 254, 372], [15, 130, 277, 369], [142, 197, 282, 383], [64, 157, 256, 350]] OPER = {operator.add: '+', operator.sub: '-', operator.mul: 'x', operator.truediv: '/'} def format_result(nums, ops, res): s = ' '.join('{} {}'.format(n,OPER[op]) for n,op in zip(nums, ops)) s += ' {} = {}'.format(nums[-1], res) return s def calc(vectors, test=lambda x: x == 1000.): for vv in permutations(vectors): for indexes in product((0,1,2,3), repeat=5): numbers = tuple(v[i] for i,v in zip(indexes, vv)) for operations in permutations(OPER): res = reduce(lambda x,y,n=count(0): operations[next(n)](x,y), numbers) if test(res): print(format_result(numbers, operations, res)) calc(vectors) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload