📜  Python - 检查列表中的替代峰值元素

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

Python - 检查列表中的替代峰值元素

给定一个列表,任务是编写一个Python程序来测试它是否是交替的,即下一个和前一个元素在整个列表中要么更小要么更大。

方法#1:使用循环

在这种情况下,我们使用条件 if 语句检查每个元素的下一个和前一个元素是更小还是更大,如果发现任何变化,结果将被标记为 false 并退出循环。

Python3
# Python3 code to demonstrate working of
# Test for alternate peak List
# Using loop
  
# initializing list
test_list = [2, 4, 1, 6, 4, 8, 0]
               
# printing original list
print("The original list is : " + str(test_list))
  
res = True 
for idx in range(1, len(test_list) - 1):
      
    # breaking if not alternate peaks
    if not ((test_list[idx - 1] < test_list[idx] 
             and test_list[idx + 1] < test_list[idx])
            or (test_list[idx - 1] > test_list[idx] 
                and test_list[idx + 1] > test_list[idx])):
        
        res = False
          
# printing result
print("Is list forming alternate peaks ? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test for alternate peak List
# Using all() + generator expression
  
# initializing list
test_list = [2, 4, 1, 6, 4, 8, 0]
               
# printing original list
print("The original list is : " + str(test_list))
  
# checking for all the elements for alternate peaks 
# one liner solution to problem
res = all(((test_list[idx - 1] < test_list[idx]
            and test_list[idx + 1] < test_list[idx]) 
           or (test_list[idx - 1] > test_list[idx] 
               and test_list[idx + 1] > test_list[idx]))
          for idx in range(1, len(test_list) - 1))
          
# printing result
print("Is list forming alternate peaks ? : " + str(res))


输出:

The original list is : [2, 4, 1, 6, 4, 8, 0]
Is list forming alternate peaks ? : True

方法#2:使用all() +生成器表达式

在这里,我们使用 all() 执行检查所有元素以获得替代峰值的任务,并且生成器表达式用于遍历整个列表。

蟒蛇3

# Python3 code to demonstrate working of
# Test for alternate peak List
# Using all() + generator expression
  
# initializing list
test_list = [2, 4, 1, 6, 4, 8, 0]
               
# printing original list
print("The original list is : " + str(test_list))
  
# checking for all the elements for alternate peaks 
# one liner solution to problem
res = all(((test_list[idx - 1] < test_list[idx]
            and test_list[idx + 1] < test_list[idx]) 
           or (test_list[idx - 1] > test_list[idx] 
               and test_list[idx + 1] > test_list[idx]))
          for idx in range(1, len(test_list) - 1))
          
# printing result
print("Is list forming alternate peaks ? : " + str(res))

输出:

The original list is : [2, 4, 1, 6, 4, 8, 0]
Is list forming alternate peaks ? : True