这是pythonic,什么是pythonic?注意:我的解决方案通过了所有测试用例

时间:2017-06-27 11:18:39

标签: python

问题:

编写一个名为remove_duplicates的函数,它将采用一个名为string的参数。 此字符串输入将只包含a-z之间的字符,并应删除字符串中的所有重复字符。

返回一个包含两个值的元组: 仅包含唯一排序字符的新字符串。 删除的重复总数。

示例:

remove_duplicates(' aaabbbac')=> (' abc',5)

我的解决方案:

def remove_duplicates(string):
    no_dups = list(set(string))
    no_dups.sort()
    total_dups = len(string) - len(no_dups)
    return "".join(no_dups), total_dups

的TestCases;

import unittest;

class Test(unittest.TestCase):
    def test_output_is_correct(self):
        result1 = remove_duplicates('aaabbbac')
        result2 = remove_duplicates('a')
        result3 = remove_duplicates('thelexash')

        self.assertIsInstance(result1, tuple, msg='Incorrect output type')
        self.assertEqual(result1, ('abc', 5), msg='Incorrect output')

        self.assertIsInstance(result2, tuple, msg='Incorrect output type')
        self.assertEqual(result2, ('a', 0), msg='Incorrect output')

        self.assertIsInstance(result3, tuple, msg='Incorrect output type')
        self.assertEqual(result3, ('aehlstx', 2), msg='Incorrect output')

    def test_output_is_correct_hidden(self):
        result1 = remove_duplicates('thisisateststring')
        result2 = remove_duplicates('letsseehowthisgoes')
        result3 = remove_duplicates('hiddenhiddenhiddenhaha')

        self.assertIsInstance(result1, tuple, msg='Incorrect output type')
        self.assertEqual(result1, ('aeghinrst', 8), msg='Incorrect output')

        self.assertIsInstance(result2, tuple, msg='Incorrect output type')
        self.assertEqual(result2, ('eghilostw', 9), msg='Incorrect output')

        self.assertIsInstance(result3, tuple, msg='Incorrect output type')
        self.assertEqual(result3, ('adehin', 16), msg='Incorrect output')

1 个答案:

答案 0 :(得分:0)

Pythonic足以满足我的口味,不过也许我会这样写:

def remove_duplicates(string):
    no_dups = ''.join(sorted(set(string)))
    return (no_dups, len(string) - len(no_dups))