【问题标题】:How to get max odd number in a list using recursion python?如何使用递归python获取列表中的最大奇数?
【发布时间】:2021-12-13 10:09:48
【问题描述】:

我想使用递归而不使用 max() 或 min() 函数来获取列表中的最大奇数。

这就是我到目前为止写的:

def maxOdd(L):
    if L[1:]:
        #check odd numbers only
        if L[0] % 2 == 1:
            #get largest odd number
            if L[0] > maxOdd(L[1:]):
                return L[0]
            else:
                return maxOdd(L[1:]) 
        else:
            return maxOdd(L[1:])        
    #check if list is empty
    elif not L:
        return None
    else:
        return L[0]

但是效果不好,没有通过这个测试:

print('Testing maxOdd()...', end='')
assert(maxOdd([ ]) == None)
assert(maxOdd([ 2, 4, 6 ]) == None) 
assert(maxOdd([ 2, 4, 6, 7 ]) == 7)
assert(maxOdd([ -1, -2, -3 ]) == -1)
assert(maxOdd([ 1,2,3,4,5,6,7,8,9,10,0,0,0,11,12 ]) == 11)
print('Passed!')

你能帮帮我吗?我被困了几个小时。 谢谢!

【问题讨论】:

    标签: python recursion


    【解决方案1】:

    我知道您要求一种运行递归的方法,但也许这种非递归解决方案也很有趣:

    def max_odd(find_list):
        return sorted([i for i in find_list if i%2==1])[-1]
    print(max_odd([1,2,3,4,5,8,99,9,99,8,77,6,5,44,11]))
    >99
    

    如果列表中没有奇数,代码将引发IndexError

    【讨论】:

      【解决方案2】:

      问题在于if L[0] > maxOdd(L[1:]):。由于我们正在寻找最大奇数,我们只需要比较奇数值。所以如果maxOdd(L[1:]) 不奇怪,我们需要忽略它。

      def maxOdd(L):
          if L[1:]:
              if L[0] % 2 == 1:
                  x = maxOdd(L[1:])
                  #if x is odd, compare. if not rrturn L[0]
                  if x is not None and x%2==1:
                      if L[0] > x:
                          return L[0]
                      else:
                          return x
                  else:
                      return L[0]
              else:
                  return maxOdd(L[1:])
          elif not L:
              return None
          elif L[0]%2==1:
              return L[0]
          else:
              return None
      

      【讨论】:

      • IndexError: 列表索引超出范围
      • 等等,我还在更新中
      • 我认为最好将奇数测试放在 return 周围。在当前状态下,maxOdd([2]) 将返回 2 而不是 None
      • maxOdd([ 2, 4, 6 ]) 应该返回 none 而不是 6
      • @MoustafaAbada 刚刚更新,您可以立即查看
      【解决方案3】:

      在返回之前,您应该首先确保第一个项目是奇数;否则,使用您的:

      if L[1:]:
          ...
      else:
          return L[0]
      

      即使不是奇数,您也会返回第一个项目。

      一个工作示例:

      def maxOdd(L):
          if L:
              first, *rest = L
              max_rest = maxOdd(rest)
              if first % 2 == 1 and (max_rest is None or first > max_rest):
                  return first
              return max_rest
      

      演示:https://replit.com/@blhsing/DisguisedEveryNotification

      【讨论】:

        猜你喜欢
        • 2019-02-17
        • 2020-11-25
        • 2011-12-29
        • 1970-01-01
        • 2011-03-10
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        相关资源
        最近更新 更多