Skip to content

Instantly share code, notes, and snippets.

@Zagrebelin
Forked from vaxyzek/taneja.py
Last active January 13, 2017 09:42
Show Gist options
  • Save Zagrebelin/4df038c207465aa83d14ba9c536216a9 to your computer and use it in GitHub Desktop.
Save Zagrebelin/4df038c207465aa83d14ba9c536216a9 to your computer and use it in GitHub Desktop.
#! /usr/bin/python3.6
import datetime
import itertools
def show_progress(start, idx, total):
if idx == 0:
return
now = datetime.datetime.now()
speed = idx / (now - start).total_seconds()
togo = (total - idx) / speed
eta = now + datetime.timedelta(seconds=togo)
print(f'{now}: {idx} of {total} eta={eta} [{speed:0.4F} exp/s]')
def generate_product(lst, count):
yield from itertools.product(*[lst] * count)
def generate_operations(count):
operations = ['+', '-', '/', '*', '**', '']
for ops in generate_product(operations, count):
if ops.count('**') >= 2:
continue
yield ops
def generate_braces(count):
obr = ['(', '']
cbr = [')', '']
for o in generate_product(obr, count):
for c in generate_product(cbr, count):
if o.count('(') != c.count(')'):
continue
yield o, c
def check_exression(exp):
if ')(' in exp or '()' in exp:
return
try:
res = eval(exp)
if res == int(res):
return res
except (SyntaxError, ZeroDivisionError, TypeError, OverflowError) as e:
pass
except Exception as e:
print(exp, type(e))
pass
def generate_expression(digits):
operations = generate_operations(len(digits) - 1)
operations = list(operations)
total = len(operations)
start = datetime.datetime.now()
for idx, ops in enumerate(operations):
show_progress(start, idx, total)
for open_braces, close_braces in generate_braces(len(digits) - 1):
exp = itertools.zip_longest(open_braces, digits, close_braces, ops, fillvalue='')
exp = sum(exp, ())
exp = ''.join(exp)
yield exp
return
def main():
digits = "123456789"
answers = {}
for exp in generate_expression(digits):
res = check_exression(exp)
if res is not None:
answers[res] = exp
with open('answer.txt', 'w') as f:
for k in sorted(answers.keys()):
if k > 0:
f.write('%d %s\n' % (k, answers[k]))
if __name__ == '__main__':
s = datetime.datetime.now()
main()
e = datetime.datetime.now()
print(e-s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment