【问题标题】:How to write a program that checks if a word supplied as the argument is an Isogram如何编写一个程序来检查作为参数提供的单词是否是 Isogram
【发布时间】:2017-09-08 20:20:46
【问题描述】:

我需要编写这个 python 代码来检查一个单词是否是等距图,并被要求使用一个方法并在以布尔值结束之前调用一个元组。这是给我的测试代码,我和这个代码斗争了一天多没有解决方案。

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'
      )

【问题讨论】:

  • 你测试过但没有工作的代码在哪里。很难知道到底出了什么问题?
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。
  • 您能解释一下所示代码的相关性并举例说明所需的输入和输出吗?

标签: python methods boolean tuples


【解决方案1】:

您可以使用len(set(s)) == len(s) 测试等值线,也就是说,如果唯一字符集的长度等于字符串的长度,则该字符串是等值线。

在我看来,函数应该是这样的:

def is_isogram(s):
    if not isinstance(s, str):
       raise TypeError('String inputs allowed only')
    return len(set(s)) == len(s)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 2012-12-18
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    相关资源
    最近更新 更多