简体   繁体   English

Python:行程编码

[英]Python: Run-Length Encoding

I'm getting an error if the input only contains a character without a number attached to it. 如果输入仅包含不带数字的字符,则会出现错误。 For example, if the user were to input "a2bc" the output should be "aabc". 例如,如果用户输入“ a2bc”,则输出应为“ aabc”。 I have to meet the run-length format. 我必须满足游程长度格式。 The decode function works if its "a2b1c1". 如果解码功能的“ a2b1c1”有效。 The single character doesn't recognize any of it. 单个字符无法识别任何字符。 I played with the conditions and debugger. 我玩了条件和调试器。 I can't seem to meet the format for run-length. 我似乎无法满足游程长度的格式。

The code displayed below were my attempts. 下面显示的代码是我的尝试。 I commented on the block where I tried to fix my problems. 我在试图解决问题的区块上发表了评论。

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)

(Note: the output for test2 should be "aabbbc" ) (注意:test2的输出应为"aabbbc"
Thank you so much. 非常感谢。

This requires two changes: as you already figured out, if num is not actually a number, then you only use the char once and skip one character ahead. 这需要进行两项更改:正如您已经知道的那样,如果num实际上不是数字,则只需使用一次char,然后跳过一个字符。 Otherwise you use the number and skip two characters ahead. 否则,您将使用数字并在前面跳过两个字符。 But you also need to handle a single character without a number at the end of your string. 但是,您还需要处理单个字符,字符串末尾没有数字。 You can solve this by not only checking if user_input is empty, but whether it only has one character - in both cases you can simply return the string. 您不仅可以检查user_input是否为空,还可以检查它是否只有一个字符来解决此问题-在两种情况下,您都可以简单地返回字符串。

def decode(user_input):
    if len(user_input) < 2:
        return user_input

    char = user_input[0]
    num = user_input[1]

    if num.isdigit():
        return char * int(num) + decode(user_input[2:])
    else:
        return char + decode(user_input[1:])

You should advance by 1 instead of 2 when the next character is not a digit (ie the 1 is implicit): 当下一个字符不是数字时(即1是隐式的),应将1而不是2提前:

def decode(user_input):
    if len(user_input) < 2 : return user_input
    multiplier,skip = (int(user_input[1]),2) if user_input[1].isdigit() else (1,1)
    return user_input[0] * multiplier + decode(user_input[skip:])

note that doing this recursively will constrain the size of the input string that you can process because of the maximum recursion limit. 请注意,由于最大递归限制,因此递归执行此操作将限制您可以处理的输入字符串的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM