codewars:Split Strings

故事扮演 提交于 2020-02-26 17:45:36

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:])
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!