codewars:Split Strings

codewars:Split Strings

Instructions

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore (’_’).

Examples:

solution(‘abc’) # should return [‘ab’, ‘c_’]
solution(‘abcdef’) # should return [‘ab’, ‘cd’, ‘ef’]
solution(’’) # should return []

我的代码

这题我是用了递归的解法,递归就在于缩小问题的规模,同时有结束的最小条件。我个人觉得一遇到递归的问题脑子会先短路一下,这题最后是挺简单的,但我还是花了时间去捋的。

def solution(s):    
    if len(s)<=1:
        if len(s)==0:
            return []
        else:
            return [s+'_']
    return [s[0:2]]+solution(s[2:])
codewars:Split Stringscodewars:Split Strings weixin_44389971 发布了6 篇原创文章 · 获赞 5 · 访问量 384 私信 关注
上一篇:Codeforces Round #303B. Equidistant String


下一篇:Spring Boot(四):Thymeleaf 使用详解