(我找不到使用负整数的最小/最大示例)
你好我正在尝试编写一个简单的程序,该程序将找到3个用户定义的整数的“最大”和“最小”。如果我只是想找到最小值和最大值,这将太容易了。我想我被要求写一个程序,求出这些数字的绝对值的最小值/最大值,然后记住是哪个数字产生了最大/最小的值,即使它是负数也是如此。 这听起来有些复杂,但这是入门课程。有人可以告诉我最简单的解决方案是什么?
当前我的程序只能找到最小/最大:
print("This program will find the \"biggest\" \n"
"and \"smallest\" of three integers. \n"
"Please enter Num1: ")
while True:
try:
nNum1 = int(input())
except ValueError:
print("Please enter an integer. \n")
continue
else:
print("You have entered " + str(nNum1) + ". \n")
break
print("Please enter Num2: ")
while True:
try:
nNum2 = int(input())
except ValueError:
print("Please enter an integer. \n")
continue
else:
print("You have entered " + str(nNum2) + ". \n")
break
print("Please enter Num3: ")
while True:
try:
nNum3 = int(input())
except ValueError:
print("Please enter an integer. \n")
continue
else:
print("You have entered " + str(nNum3) + ". \n")
break
nMin = min(abs(nNum1), abs(nNum2), abs(nNum3))
print("The *smallest* of these three numbers is " + str(nMin) + ". \n")
nMax = max(abs(nNum1), abs(nNum2), abs(nNum3))
print("The *largest* of these three numbers is " + str(nMax) + ". \n")
答案 0 :(得分:1)
仅将sorted
与abs
用作键功能,最小的数字将成为结果列表的第一项,而最大的数字将成为最后的项。
>>> a = [-5, -8, 2]
>>> sorted(a, key=abs)[0]
2
>>> sorted(a, key=abs)[-1]
-8
>>>