2016-03-08 81 views
1

在下面的代碼中,我返回給定字符串中連續數字的整數值。在遞歸中只打印一個列表

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] 
+0

取出括號'[壓縮(S [cons_length:])]' – zondo

+0

@zondo如果我這樣做,我得到一個錯誤,說'TypeError:只能連接列表(不是「int」)列表' – jape

+1

啊,是的。無論如何,無論如何,在任何情況下你會返回一個整數(例如'return 0'),改變它返回一個列表:'return [0]' – zondo

回答

0

當你返回一個列表,[what_is_returned]將是一個嵌套列表,但是當你返回一個整數,它僅僅是一個列表。取而代之的是,(在compress()),始終返回一個列表,當你用什麼返回刪除括號:

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 [] 
    cons_length = consecutive_length(S) 
    return [cons_length] + compress(S[cons_length:]) 
1

你還有另外一種方法來使用itertools.groupby()

from itertools import groupby 

s = '1111000000001111000111111111111111' 
answer = [len([digit for digit in group[1]]) for group in groupby(s)] 
print(answer) 

輸出

[4, 8, 4, 3, 15] 
1

在這裏你去:

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 [] 
    cons_length = consecutive_length(S) 
    return [cons_length] + compress(S[cons_length:])