Created
July 3, 2017 17:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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