有趣!我不得不嘗試它,它是Python,希望你不介意。它運行在大約28秒時,PyPy 1.8,Core 2 Duo處理器1.4
from __future__ import division
from math import log
from operator import add, sub, mul
div = lambda a, b: float(a)/float(b)
years = set(range(2012, 2113))
none = lambda a, b: a * 10 ** (int(log(b, 10)) + 1) + b
priority = {none: 3, mul: 2, div: 2, add: 1, sub: 1}
symbols = {none: '', mul: '*', div: '/', add: '+', sub: '-', None: ''}
def evaluate(numbers, operators):
ns, ops = [], []
for n, op in zip(numbers, operators):
while ops and (op is None or priority[ops[-1]] >= priority[op]):
last_n = ns.pop()
last_op = ops.pop()
n = last_op(last_n, n)
ns.append(n)
ops.append(op)
return n
def display(numbers, operators):
return ''.join([
i for n, op in zip(numbers, operators) for i in (str(n), symbols[op])])
def expressions(years):
numbers = 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
operators = none, add, sub, mul, div
pools = [operators] * (len(numbers) - 1) + [[None]]
result = [[]]
for pool in pools:
result = [x + [y] for x in result for y in pool]
for ops in result:
expression = evaluate(numbers, ops)
if expression in years:
yield '%d = %s' % (expression, display(numbers, ops))
for year in sorted(expressions(years)):
print year
超級!只是爲了好奇,我試圖對你的代碼進行字節編譯,希望它比解釋器模式更快,但事實並非如此。 – lifebalance 2012-04-16 08:24:39
這是正確的,請參閱[這個答案](http://stackoverflow.com/questions/10135327/) – 2012-04-16 08:29:33