首页 > 解决方案 > 为什么在下面示例中的 for 循环中,两个示例中的每个示例中的第二个 for 循环中的结果都不完全相同

问题描述

头韵是指以相同字母开头的一系列单词。在本练习中,如果所有严格大于 3 个字符的单词都以相同的字母开头,则句子是正确的头韵。

例子:

alliteration_correct("She swam to the shore.") ➞ True
# All words >= 4 letters long begins with "s"

alliteration_correct("Maybel manages money well.") ➞ False
# "well" does not begin with an "m"

alliteration_correct("He helps harness happiness.") ➞ True

alliteration_correct("There are many animals.") ➞ False

笔记:

def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] == ll[0][0].lower():
            return True
    return False


print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))

def alliteration_correct(sentence):
    sentence = sentence.split(" ")
    ll = []
    for i in sentence:
        if len(i) > 3:
            ll.append(i)
    for x in ll:
        if x.lower()[0] != ll[0][0].lower():
            return False
    return True


print(alliteration_correct("He helps harness happiness."))

print(alliteration_correct("There are many animals."))

标签: python-3.xfor-loop

解决方案


您似乎在做的是检查长度大于 3 的单词的第一个字符是否出现。

对于不匹配返回 false 的情况是有效的,因为您不需要进一步检查,并且您只需返回 false。但相反,如果只检查长度 > 3 的第一个单词,则返回 true 是无效的。

这使得逻辑不同。希望能帮助到你。


推荐阅读