Python用两种方法编写求任意一组数的最大和最小数的函数,并求三组数的最大、最小的差值的均值
时间: 2024-06-03 15:11:10 浏览: 39
回答:
方法一:
def max_min(nums):
return max(nums), min(nums)
nums1 = [1, 2, 3, 4, 5]
nums2 = [10, 20, 30, 40, 50]
nums3 = [100, 200, 300, 400, 500]
max1, min1 = max_min(nums1)
max2, min2 = max_min(nums2)
max3, min3 = max_min(nums3)
diff1 = max1 - min1
diff2 = max2 - min2
diff3 = max3 - min3
mean_diff = (diff1 + diff2 + diff3) / 3
print("Max and Min of nums1: ", max1, min1)
print("Max and Min of nums2: ", max2, min2)
print("Max and Min of nums3: ", max3, min3)
print("Mean difference: ", mean_diff)
方法二:
def max_min(nums):
max_num, min_num = nums[0], nums[0]
for num in nums:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
return max_num, min_num
nums1 = [1, 2, 3, 4, 5]
nums2 = [10, 20, 30, 40, 50]
nums3 = [100, 200, 300, 400, 500]
max1, min1 = max_min(nums1)
max2, min2 = max_min(nums2)
max3, min3 = max_min(nums3)
diff1 = max1 - min1
diff2 = max2 - min2
diff3 = max3 - min3
mean_diff = (diff1 + diff2 + diff3) / 3
print("Max and Min of nums1: ", max1, min1)
print("Max and Min of nums2: ", max2, min2)
print("Max and Min of nums3: ", max3, min3)
print("Mean difference: ", mean_diff)
阅读全文