这是 Allen B. Downey 的 Think Python: How to Think Like a Computer Scientist 中的问题
给我一个包含三个连续双字母的单词。我会给你一些几乎符合条件的词,但不符合条件。例如,委员会一词,c-o-m-m-i-t-t-e-e。除了潜入其中的“i”之外,这会很棒。或密西西比州:M-i-s-s-i-s-s-i-p-pi。如果你能把那些 i 去掉,那就有用了。但有一个单词有三对连续的字母,据我所知,这可能是唯一的单词。当然大概还有500个,但我只能想到一个。这个词是什么?编写一个程序来找到它。
我的代码不起作用,所以我检查了解决方案,但仍然对该解决方案有疑问。
问题1:这是我的代码,但输出是
fin = open('words.txt.py')
lines = fin.readline()
def carplay1(word):
for lines in fin:
word = lines.strip
return word
i = 0
j = i+1
while j<len(word):
for check in range(3):
if word [i] != word[j]:
return False
else:
i = i+1
j = j+1
print(word)
print(carplay1(word))
问题2:我已经用单词 ('abbcdeeffgg') 测试了给定的代码,即使它不是字典中存在的单词,但我想确保解决方案中的代码可以用三个连续的单词来测试单词单词后面有双字母。但输出结果为False。 我认为问题在于“i = i + 1 -2*count”这一行 我该如何更正代码?
def is_triple_double(word):
i = 0
count = 0
while i<len(word)-1:
if word [i] == word [i+1]:
count = count+1
if count == 3:
return True
i = i + 2
else:
i = i + 1 - 2*count
count = 0
return False
print(is_triple_double('abbcdeeffgg'))
您只是 return 语句的嵌套有问题。在 if 条件之后,你总是去“return False”。 如果将 return 语句移到 while 循环之外
def is_triple_double(word):
i = 0
count = 0
while i<len(word)-1:
if word [i] == word [i+1]:
count = count+1
if count == 3:
return True
i = i + 2
else:
i = i + 1 - 2*count
count = 0
return False
print(is_triple_double('abbcdeeffgg')) # Returns True