请考虑以下代码:
# Generates a formula to get x using only y
from __future__ import division
from itertools import *
def f(x, y, ops=("*", "/", "-", "+", ""), infiniteprint=False, debug=False):
isiterable = hasattr(y, '__iter__')
if isiterable:
string = [str(i) for i in y]
else:
string = [str(y)]
inputs = string[:]
found = False
while True:
for i in string:
try:
result = eval(i)
except ZeroDivisionError as e:
result = ZeroDivisionError
# Just move on people, nothing to see here.
except SyntaxError as e:
result = SyntaxError
# If you have an iterable with 0 and 8 in it,
# 08 would cause it to crash, because 08 is not a valid
# expression
if result == x:
if not infiniteprint:
return i
else:
print i
prod = product(string, ops)
string = []
for j in prod:
for h in inputs:
string.append("".join(j) + h)
# Usage: f(toconstruct,constructfrom)
print f(100000, 10)
for i in range(2, 100):
print f(1337, i, debug=True)
如果你运行它,你会发现它非常慢。这是因为python是如此之慢(并且c(++)更适合这个问题),这只是解决问题的低效方法,还是仅仅是一个众所周知的难题? 编辑:我试图找到导致x的最短和,只使用y中的数字,以及运算符*,/, - 和+。