Python:运行长度编码

如果输入只包含一个没有附加数字的字符,我会收到一个错误。例如,如果用户要输入“a2bc”,则输出应为“aabc”。我必须满足游程格式。如果是“a2b1c1”,则解码功能有效。单个字符无法识别其中任何一个。我玩过条件和调试器。我似乎无法满足运行长度的格式。


下面显示的代码是我的尝试。我评论了我试图解决我的问题的块。


def decode(user_input):


    if not user_input:

        return ""


    else:

        char = user_input[0]

        num = user_input[1]


        if num.isdigit():

            result = char * int(num)


        # elif num.isalpha():

        #     # this should skip to the next two characters


        else:

            result = char * int(num)


        return result + decode(user_input[2:])


test1 = decode("a2b3c1") 

test2 = decode("a2b3c")

print(test1)

print(test2)


(注意:test2 的输出应该是"aabbbc")非常

感谢。


阿晨1998
浏览 208回答 2
2回答

MM们

这需要两个更改:正如您已经发现的,如果num实际上不是数字,那么您只使用一次字符并跳过一个字符。否则,您使用数字并跳过前面的两个字符。但是您还需要处理字符串末尾没有数字的单个字符。您不仅可以通过检查是否user_input为空,还可以通过检查它是否只有一个字符来解决这个问题——在这两种情况下,您都可以简单地返回字符串。def decode(user_input):&nbsp; &nbsp; if len(user_input) < 2:&nbsp; &nbsp; &nbsp; &nbsp; return user_input&nbsp; &nbsp; char = user_input[0]&nbsp; &nbsp; num = user_input[1]&nbsp; &nbsp; if num.isdigit():&nbsp; &nbsp; &nbsp; &nbsp; return char * int(num) + decode(user_input[2:])&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return char + decode(user_input[1:])

SMILET

当下一个字符不是数字(即 1 是隐式的)时,您应该前进 1 而不是 2:def decode(user_input):&nbsp; &nbsp; if len(user_input) < 2 : return user_input&nbsp; &nbsp; multiplier,skip = (int(user_input[1]),2) if user_input[1].isdigit() else (1,1)&nbsp; &nbsp; return user_input[0] * multiplier + decode(user_input[skip:])请注意,由于最大递归限制,递归执行此操作将限制您可以处理的输入字符串的大小。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python