简体   繁体   中英

Question is Find the 2nd largest digit ,What is wrong with my code, I am a beginner

Question is Find the 2nd largest digit,What is wrong with my code, I am a beginner,Output is still zero

a = input("Enter your number")
max = 0
maxx  = 0

list1 = []


for i in a :
    list1.append(i)
    if i > str(max) :
        max = i
        list1.remove(max)
        for j in list1 :
            if j > str(maxx) :
            maxx = j
print(maxx)

The second for loop shouldn't have been nested and inside a conditional like that, since it would only run until the highest number was found.

The other main issue is that that even without the second for loop being nested, in a situation where a = '12345' every number is the highest the first loop finds and is therefore deleted from list1 meaning that list1 ends up completely empty.

This should work:

a = input("Enter your number: ")
max_num = 0
maxx  = 0


for i in a :
    if i > str(max_num) :
        max_num = i
        
for j in a :
    if j > str(maxx) and j < str(max_num):
        maxx = j
        
print(maxx)

or you can also do this:

nums = input('Enter numbers: ')
list1 = []

for i in nums:
    list1.append(int(i))
    
list1.sort()
print(list1[-2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM