Python程序,用于检查枢轴左侧和右侧的元素是否分别较小或较大
给定一个列表和一个索引,任务是编写一个Python程序,首先选择该索引处的元素作为枢轴元素,然后测试元素是否在其右侧较大而左侧较小。
例子:
Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12], K = 4
Output : True
Explanation : Elements at Kth index is 9, elements before that are smaller and next are greater.
Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 1], K = 4
Output : False
Explanation : Elements at Kth index is 9, elements before that are smaller but 1 is after 4th index, less than 9.
方法 1:使用循环和enumerate()
在这里,我们使用循环遍历元素,枚举用于获取索引并检查索引是否大于或小于 K,以切换测试条件。
程序:
Python3
# initializing list
test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
res = True
for idx, ele in enumerate(test_list):
# checking for required conditions
if (idx > K and ele < test_list[K]) or (idx < K and ele > test_list[K]):
res = False
# printing result
print("Is condition met ? : " + str(res))
Python3
# initializing list
test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# all() used to check for condition using one liner
res = all(not ((idx > K and ele < test_list[K]) or (
idx < K and ele > test_list[K])) for idx, ele in enumerate(test_list))
# printing result
print("Is condition met ? : " + str(res))
输出:
The original list is : [4, 3, 5, 6, 9, 16, 11, 10, 12]
Is condition met ? : True
方法 2:使用all()和enumerate()
使用 all() 执行类似的任务,它可以使用单行生成器表达式测试所需的条件,以提供更紧凑的解决方案。
程序:
蟒蛇3
# initializing list
test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# all() used to check for condition using one liner
res = all(not ((idx > K and ele < test_list[K]) or (
idx < K and ele > test_list[K])) for idx, ele in enumerate(test_list))
# printing result
print("Is condition met ? : " + str(res))
输出:
The original list is : [4, 3, 5, 6, 9, 16, 11, 10, 12]
Is condition met ? : True