How to find the second biggest number in a set of random numbers in Python

2 Answers

0 votes
import random

def find_second_max(total, rndmax):
    max_val = before_max = n = random.randint(1, rndmax)
    print(n)

    for _ in range(1, total):
        n = random.randint(1, rndmax)
        print(n)
        if n > max_val:
            before_max = max_val
            max_val = n
        elif n > before_max:
            before_max = n

    return before_max


random.seed()
second_max = find_second_max(10, 100)

print(f"The second biggest number is: {second_max}")



'''
run:

77
79
75
30
87
12
92
45
60
29
The second biggest number is: 87

'''

 



answered Oct 4 by avibootz
0 votes
import random

def find_second_max(total, rndmax):
    numbers = [random.randint(1, rndmax) for _ in range(total)]
    print(*numbers, sep='\n')

    unique_numbers = sorted(set(numbers), reverse=True)
    return unique_numbers[1] if len(unique_numbers) > 1 else None


random.seed() 
second_max = find_second_max(10, 100)

if second_max is not None:
    print(f"The second biggest number is: {second_max}")
else:
    print("Not enough unique numbers to determine a second maximum.")




'''
run:

18
52
76
49
75
85
83
62
11
71
The second biggest number is: 83

'''

 



answered Oct 4 by avibootz
...