Skip to content

Instantly share code, notes, and snippets.

@Rulexec
Last active August 29, 2015 14:18
Show Gist options
  • Save Rulexec/54b94d19837f1a82a744 to your computer and use it in GitHub Desktop.
Save Rulexec/54b94d19837f1a82a744 to your computer and use it in GitHub Desktop.
import sys
numbers = [2, 0, 1, 5, 2, 0, 1, 5]
k = len(numbers) - 1
indexed_tail = list(zip(range(k), numbers[1:]))
to_bin = 2 ** k - 1
variants = []
for n in range(to_bin):
s = numbers[0] + sum([(((n >> i) & 1) * 2 - 1) * x for (i, x) in indexed_tail])
if s == 0:
variants.append(n)
if not variants:
print('No variants')
sys.exit(0)
def calc_minus_signs(n, k):
signs = 0
for i in range(k):
if (n >> i) & 1 == 0:
signs += 1
return signs
# warning: mutation of variants
minimum = [variants.pop()]
minimum_signs = calc_minus_signs(minimum[0], k)
for n in variants:
signs = k - calc_minus_signs(n, k)
if signs < minimum_signs:
minimum = [n]
minimum_signs = signs
elif signs == minimum_signs:
minimum.append(n)
for n in minimum:
string = str(numbers[0])
for i in range(k):
sign = '-' if (n >> i) & 1 == 0 else '+'
string += ' ' + sign + ' '
string += str(numbers[i + 1])
string += ' = 0'
print(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment