📌  相关文章
📜  Python程序,用于检查枢轴左侧和右侧的元素是否分别较小或较大

📅  最后修改于: 2022-05-13 01:55:15.880000             🧑  作者: Mango

Python程序,用于检查枢轴左侧和右侧的元素是否分别较小或较大

给定一个列表和一个索引,任务是编写一个Python程序,首先选择该索引处的元素作为枢轴元素,然后测试元素是否在其右侧较大而左侧较小。

例子:

方法 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))


输出:

方法 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))

输出: