首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我的代码是冻结和使用的许多CPU的能力。(Python)

我的代码是冻结和使用的许多CPU的能力。(Python)
EN

Stack Overflow用户
提问于 2022-02-14 12:04:11
回答 1查看 72关注 0票数 1

我试图做一种人工智能类似脚本,这将理解你的短语。这项工作仍在进行中,尚未完成。

每个猜测都应该打印以下信息:

产生的案文:.脚本生成的字符串。

案文的长度:.前面提到的字符串的长度。

课文分数:.脚本将根据文本的长度和字母的大小对文本进行评分。

目标文本:.它试图产生的文本。

出于某种原因,在第一个字符串之后,代码会冻结。我希望任何人都能帮忙,谢谢!

代码语言:javascript
运行
复制
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!!")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-14 12:16:47

这是因为执行被卡在第二个无限循环中。在第一次执行之后,每次都满足条件(len(Ai)+lenVariation > len(goal)*2 or len(Ai)+lenVariation<round(len(goal)*0.5)),因此if语句永远不会被计算为True,并且不会退出while循环。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71111604

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档