计算双向元组对的Python程序
给定元组列表,计算双向元组。
Input : test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
Output : 3
Explanation : (1, 2), (2, 1); (5, 6) -> [(6, 5), (6, 5)], total 3 pairs.
Input : test_list = [(5, 6), (1, 3), (6, 5), (9, 1), (6, 5), (2, 1)]
Output : 2
Explanation : (5, 6) -> [(6, 5), (6, 5)], total 2 pairs.
方法:使用循环
在这里,我们检查每个元素是否有任何其他双向元素,一旦找到对,计数器就会增加。
Python3
# Python3 code to demonstrate working of
# Count Bidirectional Tuple Pairs
# Using loop
# initializing list
test_list = [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
# printing original list
print("The original list is : " + str(test_list))
res = 0
for idx in range(0, len(test_list)):
for iidx in range(idx + 1, len(test_list)):
# checking bidirection
if test_list[iidx][0] == test_list[idx][1] and test_list[idx][1] == test_list[iidx][0]:
res += 1
# printing result
print("Bidirectional pairs count : " + str(res))
输出:
The original list is : [(5, 6), (1, 2), (6, 5), (9, 1), (6, 5), (2, 1)]
Bidirectional pairs count : 3