0
l = [5, 4, 3, 2, 1, 100, 69]
largest = l[0]
smallest = l[0]
seclargest = 0
secsmallest = 0
a = len(l)
b = a - 1
for i in range(a):
    if l[i] > largest:
        seclargest=largest
        if b == i:
            print(seclargest)
        largest = l[i]
    if l[i] < smallest:
        if b>i:
            secsmallest = smallest
        smallest = l[i]

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)

Help, please. This code only prints the smallest and second smallest correctly but not the largest and second largest values.

wp78de
  • 18,207
  • 7
  • 43
  • 71

1 Answers1

0

If you want to do it in linear time (one for loop), you can modify your code as follows:

l = [5, 4, 3, 2, 1, 100, 69]
largest = -1e10  # initialize to large negative number
smallest = 1e10  # initialize to large positive number
seclargest = -1e9 
secsmallest = 1e9
for x in l:
    if x > largest:
        seclargest=largest
        largest = x
    elif x > seclargest:
        seclargest = x
    elif x < smallest:
        secsmallest = smallest
        smallest = x
    elif x < secsmallest:
        secsmallest = x

print(largest)
print(seclargest)
print(smallest)
print(secsmallest)

Which outputs:

100
69
1
2

You were pretty close. You just needed to add one condition for the case where the number was smaller than the largest, but larger than the second largest and one similar condition for the second smallest.

Also, you can iterate through the list simply using for x in l, there's no need to iterate over the indices.

pault
  • 41,343
  • 15
  • 107
  • 149