无限猴子定理;为什么百分比保持为零?

Infinite Monkey Theorem; why does the percentage stay at zero?

我正在关注的一本书中的一项挑战指导我编写一个程序,该程序将(最终)随机生成莎士比亚十四行诗之一的片段。 该程序运行时没有崩溃,但是,我注意到 main() 函数中的百分比打印输出保持为零,即使我认为我正在使用 float() 使其在 Python 2 中正确划分。

import random

def generate_one(strlen):
    """Generates random string of characters"""
    chars = "abcdefghijklmnopqrstuvwxyz "
    rand_list = []
    for i in range(strlen):
        rand_list.append(chars[random.randrange(len(chars))])
    rand_string = ''.join(rand_list)
    return rand_string


def test_string(test_string, answer, check):
    """Puts correctly guessed words into check_list"""
    for word in answer.split():
        if word in test_string.split() and word not in check:
            check[answer.split().index(word)] = word


def main():
    """Main program loop"""
    loop_iterations = 0
    snippet = "methinks it is like a weasel"
    check_list = []
    for i in range(len(snippet.split())):
        check_list.append("***") 
    same_words = 0
    for i in snippet.split():
        if i in check_list:
            same_words += 1
    while snippet != ' '.join(check_list):
        test_word = generate_one(len(snippet))
        test_string(test_word, snippet, check_list)
        loop_iterations += 1
        if loop_iterations % 100000 == 0:
            # the percentage stays at zero, why?
            print "Percentage: ", float(same_words) / len(snippet.split())
            print ' '.join(check_list)


main() 

这是输出示例:

Percentage:  0.0
*** it is *** a ***
Percentage:  0.0
*** it is *** a ***
Percentage:  0.0
*** it is *** a ***
Percentage:  0.0
*** it is *** a ***
Percentage:  0.0
*** it is *** a ***

如您所见,程序快速生成并存储了三个较小的词,这应该使百分比大于零。

那么为什么百分比保持为零?我错过了什么?

增加 same_words 的循环在你的主 while 循环之外,这意味着 same_words 和你的百分比输出永远不会是 0。你需要添加代码来增加它每场比赛。一种可能的方法是将 test_string 修改为 return 匹配数

def test_string(test_string, answer, check):
    """Puts correctly guessed words into check_list"""
    matches = 0
    for word in answer.split():
        if word in test_string.split() and word not in check:
            check[answer.split().index(word)] = word
            matches += 1

    return matches

然后将循环更改为

while snippet != ' '.join(check_list):
    test_word = generate_one(len(snippet))
    same_words += test_string(test_word, snippet, check_list)
    loop_iterations += 1
    if loop_iterations % 100000 == 0:
        print "Percentage: ", float(same_words) / len(snippet.split())
        print ' '.join(check_list)