我必须编写一个函数,它接受一个64字符的输入字符串0' s和1' s并让它返回该字符串的游程编码,但我认为我没有一切都正确地开始......
def compress(s):
''' takes a binary string s of length less than or equal to 64 as input
and returns another binary string as output. Output binary string will be
a run-length encoding of the input string.
'''
listS = list(s)
if s == "":
return 0
else:
listS[0] = "0"
listS[8] = "1"
listS[16] = "0"
listS[24] = "1"
listS[32] = "0"
listS[40] = "1"
listS[48] = "0"
listS[56] = "1"
newSomething = helper1(s)
return ''.join(listS)
我不太确定上面的内容是否正确,但是这个以及下面的辅助函数是我到目前为止的全部内容。我无法弄清楚如何为给定的二进制字符串创建一个行程编码字符串...
我不确定下面的这个函数是否有用,但它是作为一个开始将连续的0或1的数量转换为一个整数然后作为二进制数返回编码
def helper1(s):
'''takes in string and returns 0... but stores newString which
shows string for binary of sum of consecutive numbers
'''
sum = 0
listS = list(s)
if len(s) < 2:
return sum
elif listS[0] == listS[1]:
sum += 1
newString = numToBinary(sum)
return helper1(s[1:])
elif listS[0] != listS[1]:
sum = 0
return helper1(s[1:])
现在想一想,我甚至认为我的压缩功能的任何部分都是正确的。
我们还没有学习for或while循环所以它们不能在这里使用,我们已经专注于递归。在此先感谢您的帮助!