Last active
March 10, 2020 22:27
-
-
Save trbarron/4aa1038556615c62850454bbf4d5df13 to your computer and use it in GitHub Desktop.
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
def eval_equation(braces, input): | |
# Takes in input as a list of numbers | |
# Takes in braces as a list of "-1"s (closed |'s) and 1's (opened |'s) | |
# Returns the evaluation | |
eq = "" | |
for i in range(num_braces): | |
# map our abs logic to something the computer can interpret | |
if braces[i] == 1: eq += "abs(" | |
if braces[i] == -1: eq += ")" | |
if i != num_braces - 1: | |
# add the number | |
eq += str(input[i]) | |
# after every number, if its not followed by a ')' then you want a '*' | |
if braces[i + 1] != -1: eq += "*" | |
return eval(eq) | |
def find_results(input): | |
answers = set() # use a set to avoid repeated entries | |
# This takes all the possibilities and only evaluates those that will yield answers | |
for i in range(2 ** num_braces): | |
braces = list(str(bin(i))[2:]) | |
while len(braces) < num_braces: braces.insert(0, "-1") # prepend "0"s since it doesn't have leading 0's | |
for m in range(num_braces): braces[m] = int( | |
braces[m]) * 2 - 1 # turn the binary into -1's and 1's for our logic later | |
running_sum = 0 | |
failed_attempt = False | |
for m in range(num_braces): | |
running_sum += braces[m] | |
if running_sum < 0: failed_attempt = True # if we ever have the sum be negative that means we had more closed braces than open | |
if sum(braces) == 0 and not failed_attempt: answers.add( | |
eval_equation(braces, input)) # sum must be 0 since opens must equal closeds | |
return(answers,len(answers)) | |
for i in range(40): | |
input = [-1 * j -1 for j in range(2*i-1)] | |
num_braces = len(input) + 1 | |
a,b = find_results(input) | |
print("input: ",input) | |
print("results: ",b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if the input = [-1,-2,-3,-4,-5,-6,-7,-8,-9],
output is :
{-375, -371, 269, -241, 15, 273, 145, -99, -225, -95, -215, -213, 171, 187, -953, -437, 85, -169, -423, 221, 93, 479, -33, -415, 97, -541, -285, -25, 105, -405, -21, -147, 109, -1041, -385, 115, -139, -1031, -129}
39
showing us that there are 39 unique answers