我如何多线程处理这个Python程序?

2024-06-26 17:46:23 发布

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

我有一个Python脚本,它试图猜测一个短语,根据转储随机数字,直到正确的数字放在一起。显然,这是非常缓慢的,因为没有保留数字时,他们猜测正确,每个短语是随机猜测,它得到正确的机会非常渺茫

程序运行正常,我能在10秒内猜出一个两位数的短语,在30秒内猜出一个3位数的短语。以上任何一项都要花很长时间。我想知道多线程在这里是否有用。如果是这样,我将如何多线程这个程序

我以前没有在Python中使用线程的经验,这看起来有点混乱

你知道我该怎么做吗

代码:

import string
import random
import time



possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + """ '".,!?;:/\?<>-_=+"""

target = "guessme"
print("Phrase is 'guessme', so just enter 7 below.")
digits = int(input("How many digits in the phrase? \n] "))


attemptThis = ''.join(random.choice(possibleCharacters) for i in range(digits))
attemptNext = ''

completed = False
generation = 0
generationdisplay = 0



while completed == False:


    generationdisplay += 1

    print(attemptThis + " - " + str(generationdisplay))

    attemptNext = ''
    completed = True
    for i in range(digits):
        if attemptThis[i] != target[i]:
            completed = False
            attemptNext += random.choice(possibleCharacters)
        else:
            attemptNext += str(digits)
    generation += 1
    attemptThis = attemptNext


print("Phrase Cracked! That took " + str(generation) + " generation(s)." + "Phrase was: " + target)

如果你需要任何额外的信息,我很乐意提供

\鼠标电池


Tags: inimportfalsetargetstring数字randomgeneration