Skip to content

Instantly share code, notes, and snippets.

@pozorvlak
Created May 11, 2015 22:10
Show Gist options
  • Save pozorvlak/0d8077170b31090b8a5f to your computer and use it in GitHub Desktop.
Save pozorvlak/0d8077170b31090b8a5f to your computer and use it in GitHub Desktop.
Find all ways of writing 100 as "1<op>2<op>3...9"
#!/usr/bin/env python
PLUS = '+'
MINUS = '-'
CONCAT = ''
ops = [PLUS, MINUS, CONCAT]
def op_sequences(n):
if n == 0:
yield []
return
for seq in op_sequences(n-1):
for op in ops:
yield [op] + seq
def interleave(xs, ys):
xi = xs.__iter__()
yi = ys.__iter__()
try:
while True:
yield xi.__next__()
yield yi.__next__()
except StopIteration:
return
for seq in op_sequences(8):
calc = ''.join(interleave(map(str, range(1, 10)), seq))
if eval(calc) == 100:
print(calc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment