用于测试列表中所有元素是否最大相隔 K 的Python程序
给定一个数字列表,任务是编写一个Python程序来测试所有元素的最大间隔是否为 K。
例子:
Input : test_list = [475, 503, 425, 520, 470, 500], K = 100
Output : True
Explanation : Maximum element is 520 and minimum is 425, 520-425 = 95, which is less than 100, hence elements are in range.
Input : test_list = [475, 503, 425, 540, 470, 500], K = 100
Output : False
Explanation : Maximum element is 540 and minimum is 425, 520-425 = 115, which is more than 100, hence elements are not in range.
方法#1:使用sort()
在这里,我们执行排序元素的任务,以获取使用 sort() 可访问的最小和最大元素。下一步是获取它们之间的差异,如果小于范围,则返回 True。
Python3
# Python3 code to demonstrate working of
# Test if all elements are in range size
# Using sort()
# initializing list
test_list = [475, 503, 425, 520, 470, 500]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 100
# sorting list
test_list.sort()
# checking if greater than range
res = test_list[-1] - test_list[0] < K
# printing result
print("Are elements in range ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if all elements are in range size
# Using min() + max()
# initializing list
test_list = [475, 503, 425, 520, 470, 500]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 100
# using min() and max() rather than
# changing order
res = max(test_list) - min(test_list) < K
# printing result
print("Are elements in range ? : " + str(res))
输出:
The original list is : [475, 503, 425, 520, 470, 500]
Are elements in range ? : True
方法 #2:使用min() + max()
min() 和 max() 分别用于获取最小和最大元素,而不是更改排序或原始列表,它们之间的差异得到所需的结果。
蟒蛇3
# Python3 code to demonstrate working of
# Test if all elements are in range size
# Using min() + max()
# initializing list
test_list = [475, 503, 425, 520, 470, 500]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 100
# using min() and max() rather than
# changing order
res = max(test_list) - min(test_list) < K
# printing result
print("Are elements in range ? : " + str(res))
输出:
The original list is : [475, 503, 425, 520, 470, 500]
Are elements in range ? : True