在递归中只打印一个列表

时间:2016-03-08 23:31:53

标签: python list recursion binary compression

在下面的代码中,我返回给定字符串中连续数量的整数值。

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语句时,将返回以下内容:

>>> print (compress('1111000000001111000111111111111111'))
[4, [8, [4, [3, [15, 0]]]]]

我真的希望返回以下内容:

>>> print (compress('1111000000001111000111111111111111'))
[4, 8, 4, 3, 15]

3 个答案:

答案 0 :(得分: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 :(得分: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:])

答案 2 :(得分: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:])