Exercism.i上Python Pangram Checker中的错误

2024-04-27 17:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解决Exercism.io的Python轨迹上的this问题,并通过了除大小写和标点混合测试以外的所有测试,只有小写、数字和下划线。有10个测试,我目前有四个不正确的。这是我的密码

def is_pangram(sentence):
alphabet = "abcdefghijklmnopqrstuvwxyz"
if alphabet in sentence:
    return True
else:
    return False

测试代码如下:

class PangramTest(unittest.TestCase):
def test_empty_sentence(self):
    self.assertIs(is_pangram(""), False)

def test_perfect_lower_case(self):
    self.assertIs(is_pangram("abcdefghijklmnopqrstuvwxyz"), True)

def test_only_lower_case(self):
    self.assertIs(is_pangram("the quick brown fox jumps over the lazy dog"), True)

def test_missing_the_letter_x(self):
    self.assertIs(
        is_pangram("a quick movement of the enemy will jeopardize five gunboats"),
        False,
    )

def test_missing_the_letter_h(self):
    self.assertIs(is_pangram("five boxing wizards jump quickly at it"), False)

def test_with_underscores(self):
    self.assertIs(is_pangram("the_quick_brown_fox_jumps_over_the_lazy_dog"), True)

def test_with_numbers(self):
    self.assertIs(
        is_pangram("the 1 quick brown fox jumps over the 2 lazy dogs"), True
    )

def test_missing_letters_replaced_by_numbers(self):
    self.assertIs(is_pangram("7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog"), False)

def test_mixed_case_and_punctuation(self):
    self.assertIs(is_pangram('"Five quacking Zephyrs jolt my wax bed."'), True)

def test_case_insensitive(self):
    self.assertIs(is_pangram("the quick brown fox jumps over with lazy FX"), False)

我错过了什么?在这个概念上,有没有什么方面我还没有掌握,我应该做进一步的研究


Tags: thetestselffalsetrueisdefquick
1条回答
网友
1楼 · 发布于 2024-04-27 17:09:02

这是:

alphabet = "abcdefghijklmnopqrstuvwxyz"
if alphabet in sentence:

正在检查整个字符串,即字符串abcdefghijklmnopqrstuvwxyz,是否在句子中。检查字符串中的每个字母是否在句子中是而不是

从目前的情况来看,只有测试的字符串包含精确的序列abcdefghijklmnopqrstuvwxyz,程序才会返回true。除了第二个测试外,没有一个测试包含该字符串,但是由于有两个测试应该返回false,所以这些测试是通过的

检查每个字母的方法看起来是这样的(当然有更好的/更多的python方法,只是试图传达检查每个字母的概念,而不是检查整个大字符串):

def is_pangram(sentence):
    alphabet = "abcdefghijklmnopqrstuvwxyz"

    for char in alphabet: 
        if char not in sentence.lower(): 
            return False

    return True

相关问题 更多 >