python-3.x - 为什么在下面示例中的 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."))
解决方案
您似乎在做的是检查长度大于 3 的单词的第一个字符是否出现。
对于不匹配返回 false 的情况是有效的,因为您不需要进一步检查,并且您只需返回 false。但相反,如果只检查长度 > 3 的第一个单词,则返回 true 是无效的。
这使得逻辑不同。希望能帮助到你。
推荐阅读
- javascript - 反应 npm 启动命令
- c++ - 如何在 C++ 中将十六进制值转换为整数?
- android - 如何在 Flutter 中实现 Photoeditor
- sql - IS NULL 检查不适用于 JPA SQL 查询中的列表
- html - 在 Jquery 中相乘
- database - 如何仅更新数据库转储中的某些属性(sql/text/csv 或任何其他格式)
- java - 错误:缺少 JavaFX 运行时组件,需要运行此应用程序(使用 Maven)
- ios - Swift - 在 swift 类中使用 AppDelegate
- java - Java 上是否有任何堆外无锁数据结构(列表、集合、映射等)?
- spinnaker - Spinnaker 管道未删除已删除的 gcr 图像标签