这是低效的,缓慢的,还是众所周知的困难?

2024-05-13 18:36:16 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码:

# 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++)更适合这个问题吗?这只是解决问题的一种低效方法,还是一个众所周知的难题? EDIT:我只使用y中的数字,以及运算符*、/、-和+,试图找到导致x的最短和。你知道吗


Tags: toinfromdebugimportfalseforstring