一本书中的挑战我跟着指示我写了一个程序,该程序将(最终)随机生成莎士比亚十四行诗片段。 程序运行没有崩溃,但是,我注意到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 ***
正如您所看到的,程序会快速生成并存储三个较小的单词,这些单词应使百分比高于零。
那么为什么百分比保持在零?我错过了什么?
答案 0 :(得分:1)
递增same_words
的循环超出了你的主循环,这意味着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)