亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么添加代碼的后半部分后執行會發生變化?

為什么添加代碼的后半部分后執行會發生變化?

滄海一幻覺 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 關注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號