爱丽丝明天有一篇W字文章(1≤W≤10,000),但她也是 忙着编程就麻烦了!但是,爱丽丝碰巧知道 那H.S.高中英语老师讨厌阅读和评分 长篇论文,所以她认为如果她只是提交“合理的” 满足要求但尽可能短的文章,她 可能会有些遗憾!
这样,爱丽丝想编写一个程序来生成W序列 每个单词都是任意字符串的话作为她的散文 由1个或多个小写字母(“ a” ..“ z”)组成(不一定 一个真实的英语单词)。文章将没有标点符号或 格式化,因为那些对Alice来说似乎不必要。在试图 伪装文章的性质,爱丽丝会坚持认为所有W 单词是不同的。最后,为了她的计划,她会 使W字的长度之和尽可能小。
帮助Alice生成符合以上要求的论文。
到目前为止,我认为我已经确定了一段导致无限循环的代码。但是,我找不到解决方法。我的理论:第一个if语句与另一个if语句矛盾,从而导致无限循环。当到达第三个字符单词时,它开始无限循环。
import string, math
w = int (raw_input(" "))
words = []
paragraph = ""
alphabet = string.ascii_lowercase
first_alpha = -1
second_alpha = 0
third_alpha = 1
switch_to_two_char = False
switch_to_three_char = False
def unique(s):
return len(set(s)) == len(s)
x = 0
while (x != w):
word = ""
if (x != 0):
word = " "
if (first_alpha >= 25):
first_alpha = 0
switch_to_two_char = True
elif (second_alpha >= 25):
second_alpha = 0
first_alpha += 1
elif (second_alpha >= 25 & first_alpha >= 25):
first_alpha = 0
second_alpha = 0
switch_to_three_char = True
elif (third_alpha >= 25):
second_alpha += 1
third_alpha = 0
else:
if (switch_to_two_char and not switch_to_three_char):
second_alpha += 1
if (switch_to_three_char):
third_alpha += 1
else:
first_alpha += 1
if (switch_to_two_char):
word += alphabet[second_alpha]
word += alphabet[first_alpha]
elif (switch_to_three_char):
word += alphabet[third_alpha]
word += alphabet[second_alpha]
word += alphabet[first_alpha]
else:
word += alphabet[first_alpha]
if (unique(word) == 0):
continue
if (word in words):
continue
else:
paragraph += word
words.append (word)
x += 1
print paragraph
答案 0 :(得分:2)
当second_alpha加到25时,first_alpha + 1和second_alpha返回0。因此,当first_alpha最终加到25时,second_alpha再次返回0。下一个循环,您的程序将进入此if语句。
elif (first_alpha >= 25):
first_alpha = 0
switch_to_two_char = True
然后,first_alpha和second_alpha都再次返回0。