don*_*hat 0 python algorithm python-3.x rle
我有解码问题。首先将字符串'44444'编码为'54'. (5 次 4) 现在当我想解码'54'它的空时。(它确实对字母起作用)
该算法将字符串解码'4a3b2c'为'aaaabbbcc'。现在当我想解码'4a54'它只是给出'aaaa'但正确的解码是'aaaa44444'. 我怎样才能解码这个?
这是代码:
def decode_RLE(x):
decode = ''
count = ''
for i in x:
if i.isdigit():
#append to count
count += i
else i:
decode += i * int(count)
count = ''
return decode
Run Code Online (Sandbox Code Playgroud)
您可以尝试字符串乘法:
def decode(string):
output = ''
for i in range(0, len(string), 2):
output += int(string[i]) * string[i + 1]
return output
print(decode("54"))
print(decode("4a54"))
Run Code Online (Sandbox Code Playgroud)
输出:
44444
aaaa44444
Run Code Online (Sandbox Code Playgroud)
你甚至可以使用列表理解:
def decode(s):
return ''.join(int(s[i]) * s[i + 1] for i in range(0, len(s), 2))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |