0

The goal is to ask a user for numbers and return sum, avg, min, max. How would I get the min and max without using a function?

from cs50 import get_int

n= -1 
sum = 0
while n <= 1:
    n=get_int('Type an integer>1: ')
    print('read',n)

num_of_ints_to_be_read = n

while n >= 1:
    number = get_int('type an integer: ')
    sum += number
    n -= 1

print()
print()
print('The sum is ', sum)
print('The average is ', sum / num_of_ints_to_be_read)
print('The min is ', )
print('The max is ', )

#print()
#print()

#input('type anything to finish')

#Cant use functions for min and max
bhatnaushad
  • 372
  • 1
  • 2
  • 16
Clydefrog
  • 31
  • 1
  • 1
    Your comrades who are apparently taking the same course have pasted basically the same question here every day recently I think. Please search before asking. – tripleee Feb 28 '19 at 06:10
  • Possible duplicate of https://stackoverflow.com/questions/27009247/python-find-min-max-and-average-of-a-list-array – tripleee Feb 28 '19 at 06:15

2 Answers2

1

Use a separate variable to keep track of min and max as you read them in, and only update them if a new min or max is found. Please note I added a new import math in order to help determine the min.

from cs50 import get_int
import math

n= -1 
sum = 0
min = math.inf #Set the initial min to infinity
max = 0
while n <= 1:
    n=get_int('Type an integer>1: ')
    print('read',n)

num_of_ints_to_be_read = n

while n >= 1:
    number = get_int('type an integer: ')
    if number > max:
        max = number
    if number < min:
        min = number
    sum += number
    n -= 1

print()
print()
print('The sum is ', sum)
print('The average is ', sum / num_of_ints_to_be_read)
print('The min is ', min)
print('The max is ', max)
jlewkovich
  • 2,725
  • 2
  • 35
  • 49
1

To replicate max functionality in python, you can do so with float('inf'):

if 5 < float('inf'):
    print('ok')

Likewise for min:

if 5 > float('-inf'):
    print('ok')

If you want to do max for a list of numbers, you will use a for loop to do so:

def my_max(arr):  
    if not isinstance(arr, list) and not isinstance(arr, tuple): #type checking
        print (f'{arr} is not a list or tuple')
        return arr
    max_num = arr[0]
    for i in arr:
        if not isinstance(i, float) and not isinstance(i, int): #type checking
            print (f'{i} is not a number')
            return arr
        if i < float('inf') and i > max_num:
            max_num = i
    return max_num

print (my_max([1,5,6,7,2,3]))
# 7
print (my_max([1,5,'t',7,2,3]))
# t is not a number
print (my_max(4))
# 4 is not a list or tuple
ycx
  • 3,155
  • 3
  • 14
  • 26