【问题标题】:write a python code to find out max and second max number from a list using only one loop编写一个 python 代码,仅使用一个循环从列表中找出最大和第二个最大数
【发布时间】:2019-08-06 20:01:39
【问题描述】:

编写一个 python 代码,仅使用一个循环从列表中找出最大和第二个最大数

查找第二大的Python程序 列表中的数字

数字列表 - 列表长度至少为 2

list1 = [10, 20, 4, 45, 99] 

max=max(list1[0],list1[1]) 
secondmax=min(list1[0],list1[1]) 

for i in range(2,len(list1)): 
   if list1[i]>max: 
      secondmax=max
      max=list1[i] 
   else: 
      if list1[i]>secondmax: 
         secondmax=list1[i] 

print("Second highest number is : ",str(secondmax)) 

【问题讨论】:

  • 您具体需要哪些帮助?
  • 我不知道你在什么样的约束下工作,但你可以在没有循环的情况下完成这个,通过对列表进行排序而不是拉出列表中的最后两项。
  • @JasonKLai 如果他排序,那么他能做的最快的是 nlog(n) ,所以我假设排序不在等式。 (除非使用带有 O(n) 的桶/基数排序)然后 list[-2:] 得到最后两个数字
  • 要知道一件重要的事情:如果最大数字出现两次,那么第二大数字是否被认为与最大数字相同,或者它是下一个最小数字? heapq.nlargest 是处理第一种情况的 Python 内置方法,但解决第二种情况的解决方案必须自定义编写。
  • 有什么问题?我会使用 heapq.nlargest,尽管我不认为教练会喜欢这样。您是否需要知道如何从您的函数中一次分配/返回多个值?只需“返回 firstmax,secondmax”(不要使用内置名称作为变量名)

标签: python python-3.x max


【解决方案1】:

一个没有排序或额外数据结构的循环:

def find_two_max(lst : list):
    if len(lst) < 2:
        raise Exception ("List size must be >= 2")

    max1=max2=float('-inf')

    for number in lst:
        if number >= max1:
            max2=max1
            max1=number
        elif number > max2:
            max2=number
    return max1, max2

l=[99, 299, 0, 2,3,4,5,1000]
print("The highest two numbers are %s , %s " % find_two_max(l))```

【讨论】:

    【解决方案2】:

    您也可以在没有for 循环的情况下通过两次调用列表中的max() 并删除第一次调用的结果:

    list1 = [10, 20, 4, 45, 99]
    list1.remove(max(list1))
    print(max(list1))
    

    但这会比在你的方法中简单地使用 for 循环要慢,因为它必须遍历列表两次。

    【讨论】:

    • OP 确实说他们只能使用一个循环;假设他们不允许用隐藏循环作弊,maxlist.remove 都涉及到list 上的隐式循环,所以这是三个循环,而不是一个。
    【解决方案3】:

    如果我理解你的答案,你可以试试这个代码(也是负数):

    list1 = [99, 20, 4, 10, 45] 
    
    if len(list1) < 2:
        raise Exception ("List size must be >= 2")
    
    first_max=list1[0]
    second_max=list1[-1]
    
    #I used the position to avoid the same number(index) for the first and second max
    position_first_max=0
    position_second_max=len(list1)-1
    
    for idx,item in enumerate(list1):
        if item>first_max:
            second_max=first_max
            position_second_max=position_first_max
            first_max=item
            position_first_max=idx
        else:
            if item>second_max and position_first_max!=idx:
                second_max=item
                position_second_max=idx
    
    print("First highest number is : ",str(first_max))
    print("Second highest number is : ",str(second_max))
    

    我在不同的位置用不同的数字进行了测试。

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      一个简单的解决方案是使用 Python 内置函数来sort() 列表。对列表进行排序后,可以使用索引拉出倒数第二项:

      list1 = [10, 20, 4, 45, 99]
      
      list1.sort()
      print( 'Highest number is : ', list1[-1] )
      print( 'Second highest number is : ', list1[-2] )
      

      【讨论】:

      • 我认为 python 使用快速排序或合并排序,所以 O(nlogn)。 OP 可能正在寻找 O(n) 解决方案
      • 你可能是对的。然而,这并不完全清楚,因为 OP 只提到了“使用一个循环”。 OP 描述它的方式,听起来更像是一个 101 作业问题。
      • 无论如何,排序显然是多余的,因为您不关心列表中任何较小值的相对顺序。
      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 2015-08-03
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多