使用字符串中字符的重复对字符串进行编码和解码



我一直在努力解决这个问题,但到目前为止我还没有运气:(所以任何指导都会很棒,尤其是因为我刚刚学习Python,所以问题是:

给定某个字符串,首先必须使用以下算法对其进行编码:

  • 对于每个字母,去掉连续的重复次数(如果有的话(,并将其连续出现的次数加上一个数字,包括第一次

完成编码后,您必须创建一个函数,使用相同的标准/假设对其进行解码

它应该如何工作的一些例子:

  • "Goooooooodddd"=>"G1o9d5">
  • "Oooo"=>"O1o3">
  • "变位符"=>"a1na1g1r1a1m1">

到目前为止,我有以下编码代码:

def encode(s) :

i = 0
while( i < len(s) - 1) : 
count = 1 
while s[i] == s[i + 1] :
i += 1
count += 1

if i + 1 == len(s):
break         
print(str(s[i]) + str(count),  
end = "")
i += 1 
print()
# Code for the driver
if __name__ == "__main__" :
encode("Goooooooooddddd")
encode("Oooo") 

通过这个,我至少得到了编码部分所需的输出。

但我实际上无法执行"解码">部分,使用此编码作为起点。

我知道这个问题很傻,但我真的想不通提前感谢对此挑战问题的指导/提示

在python中解码非常简单,因为它允许字符相乘:可能是这样的:

def decode(s):
a = list(s) # separate each character and number
i = 0
z = len(a)
while i < z-1:   #This for block checks for any 2 digit numbers
print(i, a[i])
if a[i].isdigit() and a[i+1].isdigit():
a[i] = a[i]+a[i+1]
a.pop(i+1)
print(a)
z-=1
try: 
if a[i+2].isdigit():
i-=1
except IndexError:
i-=1
i+=1
final_str = '' # the string that will have the value
for i in range(0, len(a), 2):
final_str += a[i]*int(a[i+1]) #a[i] is the character and int(a[i+1]) is the number of times. 
# They are multiplied and then added to the final string
print(final_str) # The final string is printed

感谢@Tobi208指出了这个错误。

伪代码中的解码将涉及:

  1. 逐字符扫描编码字符串
  2. 如果字符是字母,则将其添加到解码结果中
  3. 子扫描1个或多个字符的数字序列的编码字符串,直到下一个字母字符或字符串结束
  4. 将最后一个解码的字符串重复此次数减去一
  5. 从步骤1继续,直到编码字符串被完全消耗

最新更新