Skip to content

Instantly share code, notes, and snippets.

@iam4722202468
Created August 26, 2022 06:27
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 iam4722202468/317469d97be82edf950ab94ac706bf01 to your computer and use it in GitHub Desktop.
Save iam4722202468/317469d97be82edf950ab94ac706bf01 to your computer and use it in GitHub Desktop.
Given a list of numbers, check if they can be added or subtracted in a way to get a specific number
import itertools
values = [-2.24, 0.46, 2.69]
toFind = 0.91
def solve(vals, target):
counter = 0
while (counter < 2 ** (len(vals))):
sum = 0
out = ""
for x in range(0, len(vals)):
bit = (counter >> x) & 1
if (bit == 1):
sum += vals[x]
out += " + " + str(vals[x])
else:
sum -= vals[x]
out += " - " + str(vals[x])
if (abs(sum - target) < 0.00001):
print(sum, "FOUND", out)
counter += 1
for x in range(1, len(values) + 1):
for y in list(itertools.combinations(values, x)):
solve(list(y), toFind)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment