Created
August 26, 2022 06:27
-
-
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
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
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