Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Last active May 28, 2024 22:33
Show Gist options
  • Save shiracamus/db37a69e6283528c01986ce9421f6e90 to your computer and use it in GitHub Desktop.
Save shiracamus/db37a69e6283528c01986ce9421f6e90 to your computer and use it in GitHub Desktop.
from itertools import permutations
def exp(a, b, *c):
if c:
for op in '+-*/':
yield from exp(f'({a}{op}{b})', *c)
yield from exp(f'({b}{op}{a})', *c)
for i in range(1, len(c) + 1):
yield from exp(*c[:i], f'({a}{op}{b})', *c[i:])
yield from exp(*c[:i], f'({b}{op}{a})', *c[i:])
else:
for op in '+-*/':
yield f'({a}{op}{b})'
yield f'({b}{op}{a})'
def make(numbers, target):
for e in set(e for n in permutations(numbers) for e in exp(*n)):
try:
if eval(e) == target:
yield e
except ZeroDivisionError:
pass
def main():
print(list(make([1, 1, 9, 9], 10)))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment