yahoo911emil
yahoo911emil

Reputation: 49

How to find min and max in python?

I have a school work that requires finding the average and the min and max, but I have no clue how to find the min and max, the teacher said we cant use the built in min max in python and also no sorting.I already got the average, just need to do the min and max, here is my code.

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)

Upvotes: 0

Views: 858

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174696

Add the below lines to your code.

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

Update:

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)   

If there is a blank line exists inbetween then the above won't work. You need to put the code inside try except block.

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) 

Upvotes: 4

Fred Mitchell
Fred Mitchell

Reputation: 2161

If you learn how to think about these types of problems, it should all fall into place.

  • If you have no numbers, what is the min/max?
  • If you have one number, what is the min/max?
  • If you have n numbers, where n is greater than 1, what are the min and max?

Upvotes: 0

dgsleeps
dgsleeps

Reputation: 700

Maybe you could find the max and the min by searching into a number list:

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

Upvotes: 1

Related Questions