我的代码冻结并使用了很多 CPU 功能。 (Python)

My code is freezing and using to much CPU power. (Python)

我正在尝试制作一种类似 AI 的脚本,它会计算出您的短语。它仍在进行中,尚未完成。
每次猜测都应打印以下信息:
产生的文本: ......... 脚本产生的字符串。
文字的长度: ... 前面提到的字符串的长度。
文本的评分:..... 脚本会根据文本的长度和其中包含的字母对文本进行评分。
目标文本:......................它试图生成的文本。
出于某种原因,在第一个字符串之后代码冻结。我希望任何人都可以提供帮助,在此先感谢!

import random

posAlpha = ["a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "l", "m", "n", "o", "p",
            "q", "r", "s", "t", "u", "v", "w", "x",
            "y", "z", "A", "B", "C", "D", "E", "F",
            "G", "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z", "!", "?", ",", ".",
            " ", "&", "0", "1", "2", "3",
            "4", "5", "6", "7", "8", "9"]

def scoreText(input, goal):
    output = 0-abs(len(input)-len(goal))
    for i in range(len(min(input, goal, key=len))):
        if not (input[i] in goal):
            output+=0
        elif not (input[i] == goal[i]):
            output += 1
        else:
            output += 2
    if output < 1:
        return 1
    else:
        return output

goal = input("Target phrase: ")
score = 0
Ai=""
for i in range(random.randrange(round(len(goal)*0.5), len(goal)*2)):
    Ai = Ai+ random.choice(posAlpha)

score = scoreText(Ai, goal)
print("Result:        " + Ai)
print("Result Length: " + str(len(Ai)))
print("Goal:          " + goal)
print("Score:         " + str(score))
print()

while True:
    oldAi = Ai
    Ai = ""
    for i in range(len(Ai)-1):
        if (score == 1 or random.randrange(1, score) == 1):
            Ai = Ai+random.choice(posAlpha)
        else:
            Ai = Ai+oldAi[i]
    while True:
        lenVariation=random.randrange(-4, 4)
        if not (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)):
            if lenVariation > 0:
                for i in range(lenVariation):
                    Ai = Ai+ random.choice(posAlpha)
                    break
            elif lenVariation < 0:
                for i in range(lenVariation):
                    AI=Ai[:-1]
                    break
    score = scoreText(Ai, goal)
    print("Result:        " + Ai)
    print("Result Length: " + str(len(Ai)))
    print("Goal:          " + goal)
    print("Score:         " + str(score))
    print()
input("Goal Achived!!")

是因为执行卡在了第二次死循环。条件 (len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)) 在第一次执行后每次都满足,因此 if 语句永远不会评估为 True 并且 while 循环永远不会退出。

此外,请注意,您的 break 语句仅存在于 for 循环中,而不存在于 while 循环中,因此永远不会执行第二次 break 之后的语句。