【发布时间】: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