字符串操作题目01

在codewar上看到过一些适合初学者的题目。在这里尽量每天总结几道题。积累下来要是分分类,可能会对大家更有帮助。

今天的题目是关于字符串操作的。

题目1:

完成一个函数accum,输入为一个字符串,输出如下示例。

accum("abcd")    # "A-Bb-Ccc-Dddd"
accum("RqaEzty") # "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt")    # "C-Ww-Aaa-Tttt"

看懂了的话就直接在下面的模版里敲代码吧。


#coding=utf-8
import unittest
def accum(s):
    #你的代码
    return None

class STestCase(unittest.TestCase):
    def testcase(self):
        self.assertEqual(accum("ZpglnRxqenU"), "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu")
        self.assertEqual(accum("NyffsGeyylB"), "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb")
        self.assertEqual(accum("MjtkuBovqrU"), "M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu")
        self.assertEqual(accum("EvidjUnokmM"), "E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm")
        self.assertEqual(accum("HbideVbxncC"), "H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc")

if __name__ == "__main__":
    unittest.main()

在注释处写好你的code,然后运行就可以利用单元测试直接测试一下。

题目2:

实现一个函数duplicate_count,对输入的字符串进行重复字符判断,如下例子所示

"abcde" -> 输出0 #
"aabbcde" -> 输出2 # 'a' and 'b'
"aabBcde" -> 输出2 # 'a' and 'b'
"indivisibility" -> 输出1 # 'i'
"Indivisibilities" -> 输出2 # 'i' and 's'
"aA11" -> 输出2 # 'a' and '1'
"ABBA" -> 输出2 # 'A' and 'B'

看懂了的话就直接在下面的模版里敲代码吧。


#coding=utf-8
import unittest
def duplicate_count(s):
    #你的代码
    return None

class STestCase(unittest.TestCase):
    def testcase(self):
        self.assertEqual(duplicate_count("abcde"), 0)
        self.assertEqual(duplicate_count("aabbcde"), 2)
        self.assertEqual(duplicate_count("aabBcde"), 2)
        self.assertEqual(duplicate_count("indivisibility"), 1)
        self.assertEqual(duplicate_count("Indivisibilities"), 2)
        self.assertEqual(duplicate_count("aA11"), 2)
        self.assertEqual(duplicate_count("ABBA"), 2)

if __name__ == "__main__":
    unittest.main()

题目3:

实现一个函数longest,对输入的两个字符串进行判断,按a-z顺序输出两个字符串中不重复的字母。例如:

a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"

看懂了的话就直接在下面的模版里敲代码吧。


#coding=utf-8
import unittest
def longest(s1, s2):
    #你的代码
    return None

class STestCase(unittest.TestCase):
    def testcase(self):
        self.assertEqual(longest("aretheyhere", "yestheyarehere"), "aehrsty")
        self.assertEqual(longest("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu")
        self.assertEqual(longest("inmanylanguages", "theresapairoffunctions"), "acefghilmnoprstuy")

if __name__ == "__main__":
    unittest.main()

要求:

测试要通过
尽量简洁

过两天会发布参考答案。另外标签会列上难度1-5级(从易到难)。答案没有最好只有更好噢。

过放荡不羁的生活,容易得像顺水推舟,但是要结识良朋益友,却难如登天。

巴尔扎克