Python – 替代元素相似度
给定元素列表,检查所有替代元素是否等于 K。
Input : test_list = [5, 3, 5, 2, 5, 8, 9], K = 5
Output : False
Explanation : 9 != 5, hence False.
Input : test_list = [4, 3, 4, 2, 4], K = 4
Output : True
Explanation : All alternates equal to 4.
方法#1:使用循环
这是解决此问题的粗略方法。在此,迭代列表中的每个元素并检查每个元素是否等于 K。
Python3
# Python3 code to demonstrate working of
# Alternate elements Similarity
# Using loop
# initializing lists
test_list = [5, 3, 5, 2, 5, 8, 5]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 5
# using flag to Flag false if any one element is not K
# using loop to check for each element
res = True
for idx, ele in enumerate(test_list):
if not idx % 2 and ele != K:
res = False
break
# printing result
print("Are all alternate elements equal to K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Alternate elements Similarity
# Using all() + generator expression
# initializing lists
test_list = [5, 3, 5, 2, 5, 8, 5]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 5
# all() to encapsulate whole logic into one expression
res = all(test_list[idx] == K for idx in range(0, len(test_list), 2))
# printing result
print("Are all alternate elements equal to K : " + str(res))
输出
The original list : [5, 3, 5, 2, 5, 8, 5]
Are all alternate elements equal to K : True
方法 #2:使用 all() + 生成器表达式
这是可以执行此任务的另一种方式。在此,我们使用 all() 检查所有元素,生成器表达式用于条件检查和迭代。
Python3
# Python3 code to demonstrate working of
# Alternate elements Similarity
# Using all() + generator expression
# initializing lists
test_list = [5, 3, 5, 2, 5, 8, 5]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 5
# all() to encapsulate whole logic into one expression
res = all(test_list[idx] == K for idx in range(0, len(test_list), 2))
# printing result
print("Are all alternate elements equal to K : " + str(res))
输出
The original list : [5, 3, 5, 2, 5, 8, 5]
Are all alternate elements equal to K : True