在下面的代码中,我返回给定字符串中连续数字的整数值。在递归中只打印一个列表
def consecutive_length(S):
if S == '':
return 0
if len(S) == 1:
return 1
if S[0] == S[1]:
return 1 + consecutive_length(S[1:])
return 1
def compress(S):
if S == '':
return 0
cons_length = consecutive_length(S)
return [cons_length] + [compress(S[cons_length:])]
当我运行这个打印语句,返回以下:
>>> print (compress('1111000000001111000111111111111111'))
[4, [8, [4, [3, [15, 0]]]]]
在那里我真的希望下面的返回到:
>>> print (compress('1111000000001111000111111111111111'))
[4, 8, 4, 3, 15]
取出括号'[压缩(S [cons_length:])]' – zondo
@zondo如果我这样做,我得到一个错误,说'TypeError:只能连接列表(不是“int”)列表' – jape
啊,是的。无论如何,无论如何,在任何情况下你会返回一个整数(例如'return 0'),改变它返回一个列表:'return [0]' – zondo