fork download
  1. from itertools import product, chain, permutations
  2. from operator import add, sub, mul, truediv
  3.  
  4. _OPS = {add: '+', sub: '-', mul: '*', truediv: '/'}
  5.  
  6. def opcycle(ops):
  7. it = iter(ops)
  8. return lambda a, b: next(it)(a, b)
  9.  
  10. def countdown(text):
  11. values = map(int, text.split())
  12. values, target = values[:-1], values[-1]
  13. for ops, perm in product(product(*[_OPS] * 5), permutations(values)):
  14. if reduce(opcycle(ops), perm) == target:
  15. return '{0} {6} {1} {7} {2} {8} {3} {9} {4} {10} {5} = {11}'.format(
  16. *chain(perm, (_OPS[op] for op in ops), (target,)))
  17. return None
  18.  
  19. print countdown('1 3 7 6 8 3 250')
  20. print countdown('25 100 9 7 3 7 881')
  21. print countdown('6 75 3 25 50 100 952')
Success #stdin #stdout 0.5s 23560KB
stdin
Standard input is empty
stdout
3 + 8 * 7 + 6 * 3 + 1 = 250
9 / 7 + 25 + 100 * 7 - 3 = 881
3 + 100 / 50 * 6 * 75 + 25 = 952