数字中间填运算符

记得以前有些杂志的广告页上常会有填数字或者运算符的小题目,比如下面这个:

(34〇5 〇 6 〇 8 〇 9 〇 1) 〇 2=2008
其中"〇"代表一个运算符 ,只可以是"+、-、*"三种运算符
使其结果得2008

用Python解决很方便,得益于自带解析表达式的eval函数,用的是穷举

from itertools import product



ops=["+","-","*"]

fmt="(34 %s 5 %s 6 %s 8 %s 9 %s 1) %s 2"



print [fmt%i for i in product(ops,repeat=6) if eval(fmt%i)==2008][0]

 结果: (34 * 5 * 6 - 8 - 9 + 1) * 2

In Ruby:

ops=["+","-","*"]

fmt="(34 %s 5 %s 6 %s 8 %s 9 %s 1) %s 2"

ops.repeated_permutation(6){|x| p fmt%x if eval(fmt%x)==2008}

 经过测试,python2.7的eval不如ruby的快,ruby1.9之后性能的确给力了

 

Mathematica实现:

Select[
 
ToString@StringForm["(34``5``6``8``9``1)``2",Sequence@@#]&/@
 
Tuples[{"+","-","*"},6],
ToExpression[#]==2008& ] 

你可能感兴趣的:(运算符)