Skip to content

Instantly share code, notes, and snippets.

@sciguy16
Created July 3, 2017 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sciguy16/0d79a241311f2dfa5d376ac796834862 to your computer and use it in GitHub Desktop.
Save sciguy16/0d79a241311f2dfa5d376ac796834862 to your computer and use it in GitHub Desktop.
python script to exhaustively search for partitions of "123456789" and their negatives that sum to 100
#!/usr/bin/python
import itertools
def pairwise_combine(array):
for i in xrange(len(array)-1):
arr = array[:i] + [''.join(array[i:i+2])] + array[i+2:]
yield arr
array = [j for j in "123456789"]
options = {tuple(array)}
def run(array):
if len(array) in [1,2]:
pass
else:
for combo in pairwise_combine(array):
options.add(tuple(combo))
run(combo)
def gen_signs(length):
signs = set()
for i in itertools.combinations_with_replacement('+-',length):
for j in itertools.permutations(i):
signs.add(j)
return signs
run(array)
for opt in options:
signs = gen_signs(len(opt))
for sign in signs:
zipped = zip(sign,opt)
numbers = [''.join(i) for i in zipped]
numbers,
if sum([int(i) for i in numbers]) == 100:
answer = ' '.join(numbers).strip('+')
operations = answer.count('+') + answer.count('-')
print "%s, with %d operations"%(answer,operations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment