Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 优化蛮力算法_Python_Optimization_Brute Force - Fatal编程技术网

Python 优化蛮力算法

Python 优化蛮力算法,python,optimization,brute-force,Python,Optimization,Brute Force,我目前正在创建一个蛮力算法,我想知道是否有一种方法可以优化我的程序,使其运行得更快,用更少的时间生成所有可能的组合 import time # 10.598227977752686 Seconds for 2 characters # 488.21563148498535 Seconds for 3 characters start = time.time() chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxy

我目前正在创建一个蛮力算法,我想知道是否有一种方法可以优化我的程序,使其运行得更快,用更少的时间生成所有可能的组合

import time

# 10.598227977752686 Seconds for 2 characters
# 488.21563148498535 Seconds for 3 characters

start = time.time()

chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '1234567890'

for char1 in chars:

    for char2 in chars:

        for char3 in chars:

            print(char1 + char2 + char3)

end = time.time()

print(end - start)
有没有办法优化这一点

您可以使用一些itertools电源:

当需要时:

28.2 ms ± 1.21 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

您的工作台是没有意义的,因为大多数时间都是在打印语句和控制台操作中度过的

也就是说,您可以使用itertools.product和string模块简化代码:

但在我这端,用一根3长度的绳子,它的速度不会快很多

4长度的字符串开始变得有趣,在我的机器上,4个嵌套python循环需要4秒钟,而itertools.productchars,repeat=4只需要3秒钟


这是因为itertools.product在主流平台上使用本机代码,这比经典的python循环c=要快得多。如果长度足够大,joint比逐字符连接快得多。删除它会使它在不到0.1秒的时间内运行3个字符。因此,您的问题的答案取决于您对数据所做的操作。你可以经常分解一些微积分,比如char1+char2
28.2 ms ± 1.21 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import itertools,string

chars = string.ascii_letters+string.digits
for t in itertools.product(chars,repeat=3):
    c = "".join(t)
    # do whatever you want with c string