Skip to content

Instantly share code, notes, and snippets.

@mopemope
Forked from nishio/gist:930325
Created April 20, 2011 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mopemope/930460 to your computer and use it in GitHub Desktop.
Save mopemope/930460 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
nums = [1, 1, 7, 7]
from operator import add, sub, mul, div
ops = {"*": mul, "+": add, "-": sub, "/": div}
def split(nums):
N = len(nums)
if nums:
head = nums[0]
if N > 1:
for n1, n2 in split(nums[1:]):
yield n1, [head] + n2
yield [head] + n1, n2
else:
yield [], [head]
yield [head], []
eqs = []
eq0 = {} # no operators
for n in nums:
eq0[float(n)] = n
eqs.append(eq0)
for num_op in range(1, 4): # 演算子の個数1〜3
eq = {}
# 使っていい合計の演算子はnum_op - 1
for num_op_lhs in range(num_op):
num_op_rhs = num_op - 1 - num_op_lhs
eq_lhs = eqs[num_op_lhs]
eq_rhs = eqs[num_op_rhs]
for lhs in eq_lhs:
for rhs in eq_rhs:
for op in ops:
try:
value = ops[op](lhs, rhs)
except ZeroDivisionError:
continue
eq[value] = (op, eq_lhs[lhs], eq_rhs[rhs])
eqs.append(eq)
for line in sorted(eqs[3].items()):
print line
"""
output:
...
(0.125, ('/', ('/', 7, ('+', 7, 1)), 7))
(0.13999999999999999, ('/', 1, ('+', ('/', 1, 7), 7)))
(0.14000000000000001, ('/', 7, ('+', ('*', 7, 7), 1)))
(0.14285714285714279, ('-', ('+', ('/', 1, 7), 1), 1))
(0.14285714285714285, ('/', ('/', ('/', 1, 7), 1), 1))
...
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment