[英]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问题是求第2大的数字,我的代码有什么问题,我是初学者,Output还是0
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.第二个
for
循环不应该嵌套在这样的条件语句中,因为它只会运行到找到最大数字为止。
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.另一个主要问题是,即使没有嵌套第二个
for
循环,在a = '12345'
的情况下,每个数字都是第一个循环找到的最高数字,因此从list1
中删除,这意味着list1
最终完全为空。
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.