尝试在列表中查找第二个最大值时出错

问题描述 投票:0回答:4

我正在尝试编写代码来查找列表的第二个最大值。

我尝试过这样的:

arr = map(int, input().split())
lista = list(arr)
max_value = lista[0]
run = lista[0]
for i in lista:
    if max_value < i:
        max_value = i
for j in lista:
    if run < j and run < max_value:
        run = j
print(run)

第二个最大值和最大值是相同的。我的程序有什么错误?

python list max
4个回答
1
投票

第二个循环中的测试不正确,请使用:

arr = map(int, input().split())
lista = list(arr)
max_value = lista[0]
run = lista[0]
for i in lista:
    if max_value < i:
        max_value = i
for j in lista:
    if run<j and j!=max_value:
        run = j
print(run)

检查的值 (

j
) 不应等于
max_value


1
投票

如果您想要列表中的第二个最大模糊,最好对列表进行排序并打印列表[-2]

示例:

my_list = [9, 6, 90, 55, 7, 90, 1]
my_list2 = list(set(my_list))
my_list2.sort()
print(my_list2[-2])

0
投票
def second_max(arr):
    first=second=0
    for i in arr:
        if i> first:
            second=first
            first=i
        elif i> second:
            second=i
    return second


  

0
投票

有趣的是,与其他常见方法相比,您的方法(经过逻辑校正)非常快

这是一个在线BENCHMARK

如果您想在自己的计算机上尝试,请提供代码:

import random 
import time 

def f1(lista):
    max1,max2 = [lista[0]]*2
    for i in lista:
        if max1 < i:
            max1 = i
            
    for j in lista:
        if max2<j and j!=max1:
            max2 = j
    return max1,max2

def f2(lista):
    max1=max(lista)
    return max1,max(set(lista)-{max1})

def f3(lista):
    return tuple(sorted(set(lista))[-2:][::-1])

def f4(lista):
    max1 = max(lista)
    max2 = max(lista, key=lambda x: min(lista)-1 if (x == max1) else x)
    return max1,max2 

def f5(lista):
    max1=max(lista)
    max2=max(x for x in lista if x < max1)
    return max1,max2 

def f6(lista):
    import heapq
    heap = [(-x, x) for x in lista]
    heapq.heapify(heap)
    _,max1=heapq.heappop(heap)
    _,max2=heapq.heappop(heap)
    return max1,max2 

def f7(lista):
    max1 = max(lista[0], lista[1]) 
    max2 = min(lista[0], lista[1]) 
    n = len(lista)
    for i in range(2,n): 
        if lista[i] > max1: 
            max2 = max1
            max1 = lista[i] 
        elif lista[i] > max2 and max1 != lista[i]: 
            max2 = lista[i]
        elif max1 == max2 and max2 != lista[i]:
                max2 = lista[i]
                
    return max1,max2      

def f8(lista):
    max1=max2=lista[0]
    for e in lista:
        if e > max1:
            max2=max1
            max1=e
        elif e > max2:
            max2=e
    return max1,max2       

def cmpthese(funcs, args=(), cnt=1000, rate=True, micro=True):
    """Generate a Perl style function benchmark"""                   
    def pprint_table(table):
        """Perl style table output"""
        def format_field(field, fmt='{:,.0f}'):
            if type(field) is str: return field
            if type(field) is tuple: return field[1].format(field[0])
            return fmt.format(field)     
        
        def get_max_col_w(table, index):
            return max([len(format_field(row[index])) for row in table])         
        
        col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
        for i,row in enumerate(table):
            # left col
            row_tab=[row[0].ljust(col_paddings[0])]
            # rest of the cols
            row_tab+=[format_field(row[j]).rjust(col_paddings[j]) for j in range(1,len(row))]
            print(' '.join(row_tab))                
            
    results={}
    for i in range(cnt):
        for f in funcs:
            start=time.perf_counter_ns()
            f(*args)
            stop=time.perf_counter_ns()
            results.setdefault(f.__name__, []).append(stop-start)
    results={k:float(sum(v))/len(v) for k,v in results.items()}     
    fastest=sorted(results,key=results.get, reverse=True)
    table=[['']]
    if rate: table[0].append('rate/sec')
    if micro: table[0].append('\u03bcsec/pass')
    table[0].extend(fastest)
    for e in fastest:
        tmp=[e]
        if rate:
            tmp.append('{:,}'.format(int(round(float(cnt)*1000000.0/results[e]))))
            
        if micro:
            tmp.append('{:,.1f}'.format(results[e]/float(cnt)))
            
        for x in fastest:
            if x==e: tmp.append('--')
            else: tmp.append('{:.1%}'.format((results[x]-results[e])/results[e]))
        table.append(tmp) 
        
    pprint_table(table)                    
    
if __name__=='__main__':
    lista=[random.randint(-1e6,1e6) for _ in range(100000)]
    funcs=[f1,f2,f3,f4,f5,f6,f7,f8]
    for f in funcs: print(f'{f.__name__}: {f(lista)}')
    cmpthese(funcs, [lista])

在最近的 Mac 上,会打印:

f1: (999991, 999978)
f2: (999991, 999978)
f3: (999991, 999978)
f4: (999991, 999978)
f5: (999991, 999978)
f6: (999991, 999978)
f7: (999991, 999978)
f8: (999991, 999978)
   rate/sec μsec/pass     f3     f6     f2     f4     f5     f7     f1     f8
f3      104   9,656.6     --  -3.1% -11.4% -45.9% -61.6% -71.2% -82.9% -87.3%
f6      107   9,358.3   3.2%     --  -8.6% -44.1% -60.3% -70.3% -82.3% -86.9%
f2      117   8,557.1  12.8%   9.4%     -- -38.9% -56.6% -67.5% -80.7% -85.7%
f4      191   5,227.9  84.7%  79.0%  63.7%     -- -29.0% -46.8% -68.3% -76.5%
f5      269   3,712.2 160.1% 152.1% 130.5%  40.8%     -- -25.1% -55.4% -66.9%
f7      360   2,779.1 247.5% 236.7% 207.9%  88.1%  33.6%     -- -40.4% -55.9%
f1      604   1,655.3 483.4% 465.3% 416.9% 215.8% 124.3%  67.9%     -- -25.9%
f8      815   1,226.9 687.1% 662.8% 597.5% 326.1% 202.6% 126.5%  34.9%     --
© www.soinside.com 2019 - 2024. All rights reserved.