Python - 检查列表是否 K 增加
给定一个 List,检查下一个元素是否总是 x + K 而不是 current(x)。
Input : test_list = [3, 7, 11, 15, 19, 23], K = 4
Output : True
Explanation : Subsequent element difference is 4.
Input : test_list = [3, 7, 11, 12, 19, 23], K = 4
Output : False
Explanation : 12 – 11 = 1, which is not 4, hence False
方法#1:使用循环
在此,我们对列表的每个元素进行迭代,并检查元素是否 K 不增加,如果找到,则将结果标记为 false 并返回。
Python3
# Python3 code to demonstrate working of
# Check if List is K increasing
# Using loop
# initializing list
test_list = [4, 7, 10, 13, 16, 19]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
res = True
for idx in range(len(test_list) - 1):
# flagging if not found
if test_list[idx + 1] != test_list[idx] + K:
res = False
# printing results
print("Is list K increasing ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Check if List is K increasing
# Using all() + generator expression
# initializing list
test_list = [4, 7, 10, 13, 16, 19]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# using all() to check for all elements
res = all(test_list[idx + 1] == test_list[idx] + K for idx in range(len(test_list) - 1))
# printing results
print("Is list K increasing ? : " + str(res))
输出
The original list is : [4, 7, 10, 13, 16, 19]
Is list K increasing ? : True
方法 #2:使用 all() + 生成器表达式
在此,我们使用 all() 检查所有 K 增加的元素,并使用生成器表达式进行迭代。
Python3
# Python3 code to demonstrate working of
# Check if List is K increasing
# Using all() + generator expression
# initializing list
test_list = [4, 7, 10, 13, 16, 19]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# using all() to check for all elements
res = all(test_list[idx + 1] == test_list[idx] + K for idx in range(len(test_list) - 1))
# printing results
print("Is list K increasing ? : " + str(res))
输出
The original list is : [4, 7, 10, 13, 16, 19]
Is list K increasing ? : True