如何在python中找到min和max?

时间:2015-03-03 02:15:23

标签: python

我的学校工作需要找到平均值和最小值和最大值,但我不知道如何找到最小值和最大值,老师说我们不能使用python中内置的min max而且没有排序。我已经得到了平均值,只需要做最小值和最大值,这是我的代码。

import random
import math
n = 0
with open("numbers2.txt", 'w') as f:
for x in range(random.randrange(10,20)): 
    numbers = random.randint(1,50) #random value between 1 to 50 
    f.write(str(numbers) + "\n")
    print(numbers)

f = open("numbers2.txt", 'r')
fr = f.read()
fs = fr.split()
length = len(fs)
sum = 0
for line in fs:
    line = line.strip()
    number = int(line)
    sum += number    
print("The average is :" , sum/length)

3 个答案:

答案 0 :(得分:4)

将以下行添加到您的代码中。

fs = fr.split()
print(min(int(i) for i in fs))
print(max(int(i) for i in fs))

<强>更新

min_num = int(fs[0])              # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `min_num` variable.
max_num = int(fs[0])              # Fetches the first item from the list and convert the type to `int` and then it assigns the int value to `max_num` variable.
for number in fs[1:]:             # iterate over all the items in the list from second element. 
    if int(number) > max_num:     # it converts the datatype of each element to int and then it check with the `max_num` variable. 
        max_num = int(number)     # If the number is greater than max_num then it assign the number back to the max_num 
    if int(number) < min_num:
        min_num = int(number)
print(max_num)
print(min_num)   

如果中间存在空行,则上述操作无效。您需要将代码放在try除了块之外。

try:
    min_num = int(fs[0])
    max_num = int(fs[0])
    for number in fs[1:]:

        if int(number) > max_num:
            max_num = int(number)

        if int(number) < min_num:
            min_num = int(number)
except ValueError:
    pass            

print(max_num)
print(min_num) 

答案 1 :(得分:1)

也许您可以通过搜索数字列表找到最大值和最小值:

numbers=[1,2,6,5,3,6]

max_num=numbers[0]
min_num=numbers[0]
for number in numbers:
    if number > max_num:
        max_num = number
    if number < min_num:
        min_num = number

print max_num
print min_num

答案 2 :(得分:0)

如果你学习如何思考这些类型的问题,它应该全部落实到位。

  • 如果没有数字,最小/最大值是多少?
  • 如果你有一个号码, 什么是最小/最大?
  • 如果你有n个数字,其中n大于 1,最小和最大是什么?