【问题标题】:Infinite Monkey Theorem; why does the percentage stay at zero?无限猴子定理;为什么百分比保持为零?
【发布时间】:2017-01-17 18:48:58
【问题描述】:

我正在阅读的一本书中的一个挑战指示我编写一个程序,该程序将(最终)随机生成莎士比亚十四行诗之一的 sn-p。 程序运行没有崩溃,但是,我注意到 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 ***

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

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

【问题讨论】:

  • @Dani 我检查了;很棒的材料。这正是我克服新手学习曲线所需要的。

标签: python python-2.7 floating-point output percentage


【解决方案1】:

递增same_words 的循环在您的主while 循环之外,这意味着same_words 和您的百分比输出都不会是0。您需要添加代码来为每次匹配增加它。一种可能的方法是修改 test_string 以返回匹配数

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)

【讨论】:

  • 我不敢相信我错过了;现在对我来说似乎很明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 2014-03-20
  • 1970-01-01
相关资源
最近更新 更多