【问题标题】:Print only one list in recursion递归只打印一个列表
【发布时间】:2016-06-23 03:39:28
【问题描述】:

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

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]

【问题讨论】:

  • 取出[compress(S[cons_length:])]中的括号
  • @zondo 如果我这样做,我会收到一条错误消息TypeError: can only concatenate list (not "int") to list
  • 啊,是的。无论如何都要这样做,但在任何情况下,如果您会返回一个整数(例如 return 0),请将其更改为返回一个列表:return [0]
  • @zondo 如果您将其作为正式答案,我会接受。谢谢!
  • 我想你其实是想回[]

标签: python list recursion binary compression


【解决方案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]

【讨论】:

    【解决方案2】:

    给你:

    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:])
    

    【讨论】:

      【解决方案3】:

      当你返回一个列表时,[what_is_returned] 将是一个嵌套列表,但是当你返回一个整数时,它只是一个列表。相反, (in 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:])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-22
        • 2016-05-07
        • 1970-01-01
        • 2018-11-08
        • 1970-01-01
        • 2022-01-18
        • 2014-11-27
        相关资源
        最近更新 更多