为了账号安全,请及时绑定邮箱和手机立即绑定

为什么添加代码的后半部分后执行会发生变化?

为什么添加代码的后半部分后执行会发生变化?

沧海一幻觉 2022-09-06 19:48:41
我在编写用于测试pangram(至少包含一次所有26个字母表的字符串)的代码时遇到了困难。当基于第一部分执行时,如下所示:def ispangram(x):    alphabet="abcdefghijklmnopqrstuvwxyz"    for i in alphabet:        if i in x.lower():            return True代码工作正常。但是如果我添加 else 条件:def ispangram(x):    alphabet="abcdefghijklmnopqrstuvwxyz"    for i in alphabet:        if i in x.lower():            return True        else i not in x.lower():            return False该代码将每个输入作为有效的全图返回。有人可以帮我了解这里出了什么问题吗?
查看完整描述

2 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

您没有检查字母表中的每个字母。您只检查单词是否包含字母 。让我们检查控制流a


def is_pangram(x):

    x = x.lower()

    alphabet="abcdefghijklmnopqrstuvwxyz"


    # we begin iteration here

    for i in alphabet:

        # we check if the letter is in the word

        if i in x:

            # we return! This will stop execution at the first True

            # which isn't always the case

            return True

        else:

            # we return again! since we've covered all cases, you will

            # only be checking for a

            return False

要解决此问题,您可以执行以下两项操作之一。使用循环,您可以只检查字母是否不在 中,如果字母不在,则返回,并在末尾返回:xFalseTrue


def is_pangram(x):

    x = x.lower()

    alphabet="abcdefghijklmnopqrstuvwxyz"


    for i in alphabet:

        if i not in x:

            return False


    # this means we made it through the loop with no breaks

    return True

或者,您可以使用运算符检查字母表中的所有字母是否都在单词中,该单词返回 ,否则返回allTrueFalse


def is_pangram(x):

    x = x.lower()

    alphabet="abcdefghijklmnopqrstuvwxyz"

    return all(i in x for i in alphabet)


查看完整回答
反对 回复 2022-09-06
?
HUX布斯

TA贡献1876条经验 获得超6个赞

对于包含任何字母的任何字符串,第一个函数将返回 true。您需要验证每个字母是否都在输入字符串中:


import string


def ispangram(x):

    x = x.lower()

    for c in string.ascii_lowercase:

        if c not in x:

            # a letter is not in the input string, so the input string is not a pangram

            return False


    # if we got here, each letter is in the input string

    return True


查看完整回答
反对 回复 2022-09-06
  • 2 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号