python - 确定字符串是否为等值图

标签 python

任务:
编写一个程序,检查作为参数提供的单词是否是 Isogram。 Isogram 是一个单词,其中没有一个字母出现超过一次。

创建一个名为 is_isogram 的方法,它接受一个参数,一个用于测试它是否为等值线图的词。此方法应返回单词的元组和指示它是否为等值线的 bool 值。

如果提供的参数是空字符串,则返回参数和 False:(argument, False)。如果提供的参数不是字符串,则引发 TypeError 并显示消息“Argument should be a string”。

例子:

is_isogram("abolishment")

预期结果:

("abolishment", True)

可见测试

from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )

我的解决方案:

def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True) 

但是函数拒绝通过一些隐藏测试:我的解决方案有什么问题?有没有另一种优雅的方式来编写这个函数?

最佳答案

我不确定你的搜索是否应该不区分大小写,所以也许你应该删除 word = word.lower(),但你的主要问题是 return 终止函数所以您当前的代码只需要在执行完所有测试后(即在循环之外)返回 True:

for char in word:
    if word.count(char) > 1:
        return (word, False)
return (word, True)

无论如何,更好的方法是使用set() 删除字符串中的所有重复项,然后比较长度;还可以使用 isinstance() 来检查 word 是否为字符串。您可以使用 if w 来检查空字符串。 return 不需要括号,逗号足以return 一个元组:

def is_isogram(word):
    if isinstance(word,str):
        w = word.lower() # assuming you want a case in-sensitive search
        return word, len(w) == len(set(w)) if w else False
    else:
        raise TypeError('Argument should be a string')

例子:

is_isogram('abolishment')
# ('abolishment', True)
is_isogram('happy')
# ('happy', False)
is_isogram('')
# ('', False)
is_isogram(1)
# TypeError: Argument should be a string

关于python - 确定字符串是否为等值图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870749/

相关文章:

python - 在wxPython中确定选定的图像

python - 如何从 GEANY (win 7) 运行脚本?

Python电话簿

python - 为有子图的图形添加标题

python - pip install pcapy 无法打开包含文件 'pcap.h'

python - 随机生成9×9列表,其中条目是1到9之间的整数,在任何行或任何列中都没有重复条目

python - 如何在 Python 中对两个数组求和?

python - pandas.tslib.Timestamp 日期匹配

python - 使用 NI-488.2 将 GPIB 转换为 USB

javascript - 我可以使用 Plotly 的自定义按钮来更新多面图中的 `shared_yaxes` 吗?