从数组中找到三个最大的数字

时间:2019-05-30 20:29:58

标签: python function

我一直在练习32个练习:https://www.w3resource.com/python-exercises/basic/

在此我应该输出三个最大的数字。

我已经处理以下代码:

def highestNumber(numbers):
  highest=numbers[0]
  for i in range(1, len(numbers)):
    if numbers[i]>highest:
      highest=numbers[i]
  return highest;  


def deleteHighestNumber(numbers):
  highest=0
  indexHighest=0
  for i in range(1, len(numbers)):
    if numbers[i]>highest:
      indexHighest=i
  numbers[indexHighest]=0
  return numbers;

input=[25, 35, 15, 16, 30, 45, 37, 39]
highestNumbers=[0,0,0]
for i in range(0,2):
  highestNumbers[i]=highestNumber(input)
  print(highestNumbers)
  print(input)
  input=deleteHighestNumber(input)
print(input)
print(highestNumbers)

这将输出:

[45, 0, 0]
[25, 35, 15, 16, 30, 45, 37, 39]
[45, 45, 0]
[25, 35, 15, 16, 30, 45, 37, 0]
[25, 35, 15, 16, 30, 45, 0, 0]
[45, 45, 0]

我希望在最后一次迭代之后,最高的NumbersArray等于:[45,39,37]。

解决方案是:

print("Input the heights of eight buildings:")
l = [int(input()) for i in range(8)]
print("Heights of the top three buildings:")
l = sorted(l)
print(*l[:4:-1], sep='\n')

在此我不理解以下代码:*l[:4:-1], sep='\n'

谢谢您的帮助!

0 个答案:

没有答案