查找最常见元素集的Python程序
给定一个集合列表,任务是编写一个Python程序来将元素与参数集进行比较,并返回一个具有最大匹配元素的元素。
例子:
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}
Output : {9, 3, 5, 7}
Explanation : Resultant set has maximum matching elements.
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {4, 6, 5, 3}
Output : {2, 3, 4, 5}
Explanation : Resultant set has maximum matching elements.
方法一:使用loop + set.intersection()
在此,我们执行使用intersection() 获取所有带有参数集的公共元素的任务,并使用len() 获取其长度,并在迭代期间比较和更新最大长度和集合。
Python3
# Python3 code to demonstrate working of
# Most common elements set
# Using loop + intersection()
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
{1, 2, 3, 4}, {9, 5, 3, 7}]
# printing original list
print("The original list is : " + str(test_list))
# initializing arg_set
arg_set = {9, 6, 5, 3}
res = set()
max_len = 0
for sub in test_list:
# updating max value on occurrence
if len(sub.intersection(arg_set)) > max_len:
max_len = len(sub.intersection(arg_set))
res = sub
# printing result
print("Max Set intersection : " + str(res))
Python3
# Python3 code to demonstrate working of
# Most common elements set
# Using loop + intersection()
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
{1, 2, 3, 4}, {9, 5, 3, 7}]
# printing original list
print("The original list is : " + str(test_list))
# initializing arg_set
arg_set = {9, 6, 5, 3}
# getting maximum length
max_len = max(len(sub.intersection(arg_set)) for sub in test_list)
# getting element matching length
res = [sub for sub in test_list if len(sub.intersection(arg_set)) == max_len][0]
# printing result
print("Set intersection : " + str(res))
输出:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Max Set intersection : {9, 3, 5, 7}
方法 2:使用max() +列表推导+交集 ()
在此,初始步骤是检查所有相交集结果的长度并使用 max() 获得最大值。接下来,提取匹配所需长度的集合的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Most common elements set
# Using loop + intersection()
# initializing list
test_list = [{4, 3, 5, 2}, {8, 4, 7, 2},
{1, 2, 3, 4}, {9, 5, 3, 7}]
# printing original list
print("The original list is : " + str(test_list))
# initializing arg_set
arg_set = {9, 6, 5, 3}
# getting maximum length
max_len = max(len(sub.intersection(arg_set)) for sub in test_list)
# getting element matching length
res = [sub for sub in test_list if len(sub.intersection(arg_set)) == max_len][0]
# printing result
print("Set intersection : " + str(res))
输出:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Max Set intersection : {9, 3, 5, 7}