python - exorcism.io 中的 pangram 问题,python 跟踪,为什么我的解决方案不起作用?
问题描述
def is_pangram(sentence):
alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
sentence = sentence.lower()
for x in alf:
if x not in sentence:
return False
else:
return True
我的代码在每种情况下都没有返回 True 。
我在 exercism.io 上使用指导模式,但 python 轨道被超额订阅,只提供主要练习的反馈。
我希望这里的 python 向导可以指出我的错误。非常感谢....
解决方案
任务是检查句子是否包含字母表中的所有字母。因此,当您找到不在句子中的第一个字母时,您可以确定情况并非如此(即),但在您检查所有字母 之前,您不能说出相反的情况(即)。return false
return true
def is_pangram(sentence):
alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
sentence = sentence.lower()
for x in alf:
if x not in sentence:
return False
return True
附录:还有一个仅限 python、鲜为人知且很少使用的for/else
语言功能,请参阅文档:for
循环可能有一个else
子句,当循环“正常”退出时调用(即不会由于 a 或异常而提前停止break
)return
。这使得以下代码成为可行的替代方案。else
与 OP 代码相比,请注意该子句的不同缩进。
def is_pangram(sentence):
alf = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
sentence = sentence.lower()
for x in alf:
if x not in sentence:
return False
else:
return True
推荐阅读
- scala - (Scala)生成一个将 1 加到一个数字的序列
- r - 在数据框上应用组合功能并保存为单个列表/数据框
- javascript - 我在哪里可以找到使用 Firefox DevTools 的 onSubmit 表单字段检查?
- c# - mvc [Remote] 标签引用单独的项目控制器
- javascript - 带有 CSS 类的 img 的 DataURL
- vuejs2 - 在 vuex 商店中通过 axios 获取单条记录
- r - sqlExecute() 查询中缺少外部字符串字符
- amazon-web-services - Amazon SageMaker 从 S3 下载文件
- azure - 如何从 Azure python sdk 创建 Azure Functions?
- python - 在 Python 脚本中使用 HTML 电子邮件使用 for 循环显示 Python 列表