检查单词是否是等值线图

时间:2017-01-26 05:45:58

标签: python function tdd

我写了一个程序来检查一个单词是否是一个等值线,但在通过测试用例后,它说“你的解决方案未能通过所有测试”

以下是测试用例:

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 or len(word) != 0:
    if not word:
        return (word, False)
    word = word.lower()
    return (word, len(set(word)) == len(word))
else:
    raise TypeError('Argument should be a string')

有谁能告诉我我做错了什么?

3 个答案:

答案 0 :(得分:0)

好的,这也有效,也通过了所有隐藏的测试。不客气

def is_isogram(word):
    '''This function tests for isogram'''
    word_set = set(word)

    if word.strip() == "":
        return (word, False)

    elif len(word) == len(word_set):
        return (word, True)

    elif type(word)!= str :
        raise TypeError

    else:
        return (word, False)

答案 1 :(得分:0)

由于这个问题涉及我一直在做的事情,我想分享我的发现,以便任何正在寻找这个问题的明确解决方案的人都使用它。

def is_isogram(word):

  word = word.lower()

  try:

      if len(word) > 0:

          for letter in word:

              if word.count(letter) > 1:

                  return (word, False)

          return (word, True)

      else:
          return ('argument', False)

  except TypeError as e:

    return "Argument should be a string: "+ str(e)

print is_isogram("")

答案 2 :(得分:0)

def is_isogram(word):
    return (word,True) if word and len(set(word)) == len(word) else (word,False)