gpt4 book ai didi

python - 猴子定理 - 选择随机字母直到生成输入字符串

转载 作者:行者123 更新时间:2023-12-01 03:42:09 26 4
gpt4 key购买 nike

我想做一个类似于无限猴子定理的代码定理指出:

a monkey hitting keys at random on a typewriter keyboard for infinite amount of time will almost surely type a given text such as the complete works of Shakespeare.

好吧,假设我们用Python替换一只猴子来生成莎士比亚的一句话?并计算试验

例如:“我认为它就像一只黄鼠狼”

这是我写的:

def Monkey_Theorem(sentence):
sentence.lower()
string_letters = 'abcdefghijklmnopqrstuvwxyz'
import random
a = []
l = ''
x = 0
trials = 0
while x < (len(sentence) - 1):
trials += 1
z = random.choice(string_letters)
if z == sentence[x]:
a.append(z)
x += 1
elif z == " ":
trials -= 1
a.append(" ")
if x > (len(sentence) - 1):
l = ''.join(l)
break
return l and trials

我将其写入 python 2.7 IDLE ,按 Enter 键然后写道:

Monkey_Theorem("methinks it is like a weasel")

之后我按了回车键..它移到了下一行并且没有出现 (>>>)

一段时间后没有结果,当我试图关闭 IDLE 时脸上露出绝望,它说程序仍在运行

问题是:

(A) while 循环是无限循环吗??
(B) 或者我的 IDLE 很慢?
(C) 其他原因
以及如何修复原因

还有一个请求以后遇到这种情况怎么判断是(A)、(B)、(C)?

最佳答案

您可以在循环中打印一些内容来查看它是否是无限的...例如,如果 z 永远不等于 sentence[x],那么您不会增加它,并且循环永远不会停止。

当您需要猜测空格字符时就会发生这种情况,因为您没有将空格字符放入字符串中。因此,即使 elif z == "": 也永远不会被输入。

这是您的代码的工作版本。

需要注意的一些事情:跟踪 al 是没有意义的。在函数结束时,您将返回与 sentence 完全相同的输入。此外,还有一个简单的导入即可获取所有英文字母。

from string import ascii_lowercase as alpha
import random

# add space character to possible choices
alpha += ' '

def Monkey_Theorem(sentence):
sentence = sentence.lower()
x = 0
trials = 0
while x < len(sentence):
trials += 1
z = random.choice(alpha)
if z == sentence[x]:
if z == " ": # this isn't really necessary
trials -= 1
print "guessed %s at trial %d" % (z, trials)
x += 1
return trials

trials = Monkey_Theorem("hello world")
print "number of trials = ", trials

输出

guessed h at trial 49
guessed e at trial 52
guessed l at trial 58
guessed l at trial 107
guessed o at trial 145
guessed at trial 157
guessed w at trial 168
guessed o at trial 197
guessed r at trial 232
guessed l at trial 248
guessed d at trial 269
number of trials = 269

关于python - 猴子定理 - 选择随机字母直到生成输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com