Python 这是低效的、缓慢的,还是众所周知的困难?
考虑以下代码:Python 这是低效的、缓慢的,还是众所周知的困难?,python,performance,Python,Performance,考虑以下代码: # 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:
# 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++)更适合这个问题),这只是解决问题的一种低效方法,还是一个众所周知的难题?
编辑:我只使用y中的数字和运算符*、/、-和+,试图找到x中的最短和。你想做什么?@sshashank124请参阅编辑。这是为了在codegolf.SE.com上进行挑战。
这是因为python太慢了吗
是什么让你说python太慢了?根据我的经验,它相当快eval
显然相当慢。您可以使用操作符
模块,它包含执行操作的函数,执行这些函数比创建字符串并对其求值要快。