确定`String`是否是等值线图

San*_*ine 0 python pattern-matching

要确定字符串是否是等值线图:

确定单词或短语是否是等值线图.等值线(也称为"非模式词")是没有重复字母的单词或短语,但允许空格和连字符多次出现.

我的尝试:

def is_isogram(string):
    word = string.lower()

    if word == "":
        return False
    elif word == " ":
        return False
    else:
        for char in word:
            if (word.count(char) > 1) and (char != " " or char != "-") and (len(word) > 0):
                return False
            else:
                return True
Run Code Online (Sandbox Code Playgroud)

但是,当传递给函数的字符串为空并且2个中心字符相同时,这会失败.

这些是单元测试:

import unittest
from isogram import is_isogram

class IsogramTest(unittest.TestCase):

    def test_empty_string(self):
        self.assertIs(is_isogram(""), True)

    def test_isogram_with_only_lower_case_characters(self):
        self.assertIs(is_isogram("isogram"), True)

    def test_word_with_one_duplicated_character(self):
        self.assertIs(is_isogram("eleven"), False)

    def test_word_with_one_duplicated_character_from_end_of_alphabet(self):
        self.assertIs(is_isogram("zzyzx"), False)

    def test_longest_reported_english_isogram(self):
        self.assertIs(is_isogram("subdermatoglyphic"), True)

    def test_word_with_duplicated_character_in_mixed_case(self):
        self.assertIs(is_isogram("Alphabet"), False)

    def test_hypothetical_isogrammic_word_with_hyphen(self):
        self.assertIs(is_isogram("thumbscrew-japingly"), True)

    def test_isogram_with_duplicated_hyphen(self):
        self.assertIs(is_isogram("six-year-old"), True)

    def test_made_up_name_that_is_an_isogram(self):
        self.assertIs(is_isogram("Emily Jung Schwartzkopf"), True)

    def test_duplicated_character_in_the_middle(self):
        self.assertIs(is_isogram("accentor"), False)

    # Additional tests for this track

    def test_isogram_with_duplicated_letter_and_nonletter_character(self):
        self.assertIs(is_isogram("Aleph Bot Chap"), False)


if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

在为这两个测试用例提供服务时,我做错了什么?

Aja*_*234 5

它是更易于使用collections.Counter,并string.ascii_lowercase只检查字母字符:

from collections import Counter
from string import ascii_lowercase

def is_isogram(s:str) -> bool:
  c = Counter(s.lower())
  return all(c[i] < 2 for i in ascii_lowercase)

tests = [('', True), ('isogram', True), ('eleven', False), ('zzyzx', False), ('subdermatoglyphic', True), ('Alphabet', False), ('thumbscrew-japingly', True), ('six-year-old', True), ('Emily Jung Schwartzkopf', True), ('accentor', False), ('Aleph Bot Chap', False)]
for a, b in tests:
  assert is_isogram(a) == b

print('all tests passed')
Run Code Online (Sandbox Code Playgroud)

输出:

all tests passed
Run Code Online (Sandbox Code Playgroud)