【问题标题】:Python: Get a number of a list of lists which has >= 3 odd numbers "Recursively"Python:获取具有> = 3个奇数“递归”的列表列表的数量
【发布时间】:2019-02-17 14:00:08
【问题描述】:

我需要帮助以递归方式获取 >= 3 个奇数的列表列表。例如, [1, 2, 3, 4, [3, 3, 3]] 返回 1,因为只有内部列表有超过 3 个奇数。 [2, 5, 5, 5, [3, 3, 3]] 返回 2,因为外循环和内循环都有超过 3 个奇数。

对我来说最困难的部分是跟踪计算奇数个数的条件。所以我想出了一个想法,在每个递归步骤中使用一个额外的参数(cnt)。

底部的伪代码不起作用,这只是我的基本想法。有人可以给我一些提示或想法吗?

    def count_even(L):
      def helper(L, cnt):
        if L is empty return 0
        elif cnt == 3 return 1 # when odd numbers >= 3 then it returns
        elif L[0] is even? return helper(L[0], count+1) # increment cnt
        elif L[0] is list? # if detects inner loop, then another recursion
          inner_list = L[0]
          return helper(inner_list[0], 0) + helper(inner_list[1:], 0)
        else: # L[0] is not even
          return helper(L[1:], count)

     # calling a helper function with cnt=0
     helper(L, 0) 

【问题讨论】:

  • 在这里尝试使用递归深度优先搜索方法。每当你遇到list,调用递归函数,然后调用你的helper函数来计算连续的奇数。

标签: python algorithm recursion


【解决方案1】:

这是一个简单的解决方案。可能更短,但这更具可读性只需计算返回 1 的几率,如果您有超过 3 个,如果您遇到 list 对象,只需再次调用您的函数。这也适用于嵌套列表。

def count_even(L):
    c = 0
    numberOfOddsInList = 0
    for i in L:
        if type(i) is list:
            numberOfOddsInList = count_even(i)
        else:
            if i % 2 == 1:
                c+=1
    return (c >= 3) + numberOfOddsInList


print(count_even([1, 2, 3, 1, [3, 3, 3,[1,1,1]]]))# returns 3 

【讨论】:

  • 我不应该使用任何循环:/
【解决方案2】:

由于您已经在使用包装器,我们可以检查一个递归,该递归计算当前列表的奇数元素以及列表元素的计数。我们也可以只使用索引来标记我们所在的位置并避免不必要的复制(此递归可以使用或不使用包装器,具体取决于您的需要):

# Returns a tuple:
# (this_list, total)
def f(L, i):
  if i == len(L):
    return (0,0)

  this_list, total = f(L, i + 1)

  if isinstance(L[i], list):
    return (this_list, total + f(L[i], 0)[1])

  if this_list == "list counted" or not (L[i] & 1):
    return (this_list, total)

  if this_list == 2:
    return ("list counted", total + 1)

  return (this_list + 1, total)

print f ([1, 2, 3, 5, [3, 3, 3, [5,5,5]]], 0) # ('list counted', 3)
print f ([1, 2, 3, 4, [3, 3, 3, [5,5,5]]], 0) # (2, 2)

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多