目标是向用户询问数字并返回总和,平均值,最小值和最大值。不使用函数如何获得最小值和最大值?
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
答案 0 :(得分:1)
使用一个单独的变量来跟踪您读入的最小值和最大值,并且只有在找到新的最小值或最大值时才进行更新。请注意,我添加了一个新的导入math
,以帮助确定最小值。
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)
答案 1 :(得分:1)
要在python中复制最大功能,可以使用float('inf')
:
if 5 < float('inf'):
print('ok')
至少分钟:
if 5 > float('-inf'):
print('ok')
如果要对一个数字列表进行最大限制,则可以使用for
循环来实现:
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