python的最大和第二大数字

2024-09-30 16:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始学习如何使用python编写代码。 在这段代码中,我想找到最大和第二大输入数字(大学教员的年龄)。 但是它不起作用! 我不知道问题出在哪里! 提前谢谢

oldest = 0
oldest2 = 0
for i in range (100):
    age = int(input())
    if age > oldest :
        oldest = age
    age = int(input())
    if age > oldest2 and age < oldest: 
        oldest2 = age
  
    if age == -1:
        break
print (oldest, oldest2)

Tags: and代码inforinputageifrange
3条回答

以下几点应该行得通。这只是你已经拥有的东西的一个微小变化。您是在寻找实现结果的最佳方式,还是有特定的要求

oldest = 0
oldest2 = 0
for i in range (100):
    age = int(input())
    if age > oldest:
        oldest2 = oldest
        oldest = age
    elif age > oldest2 and age != oldest:
        oldest2 = age

    # This is in case you have faculty members that are all the same age
    # We assume none of them are age 0
    if oldest2 == 0:
        oldest2 = oldest

    if age == -1:
        break
print (oldest, oldest2)

以下为试验数据

[10, 20, 40, 20, 5]
[10, 90, 40, 20, 5]
[100, 100, 90]
[30, 30]

结果是

[40, 20]
[90, 40]
[100, 90]
[30, 30]

每个循环会得到两次年龄,并且每个循环只考虑两个选项中的一个。你最多只能说对了一半。相反,让python为您完成这项工作。您可以将年龄收集到一个列表中,进行排序,然后提取数字

ages = []
while True:
    next_val = int(input())
    if nex_val == -1:
        break
    ages.append(next_val)
ages.sort()
print(ages[-2:])
first_oldest = 0
second_oldest = 0

while True:

    age = int(input())
    if age != -1:

        if age > first_oldest:
            second_oldest = first_oldest
            first_oldest = age

        elif second_oldest < age < first_oldest:
            second_oldest = age

        if second_oldest == 0:
            second_oldest = first_oldest
    else:
        break

print(first_oldest, second_oldest)

相关问题 更多 >