📌  相关文章
📜  获取集合元素之间所有可能差异的Python程序

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

获取集合元素之间所有可能差异的Python程序

给定一个集合,任务是编写一个Python程序来获取其元素之间所有可能的差异。

Input : test_set = {1, 5, 2, 7, 3, 4, 10, 14}
Output : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Explanation : All possible differences are computed.

Input : test_set = {1, 5, 2, 7}
Output : {1, 2, 3, 4, 5, 6}
Explanation : All possible differences are computed.

方法#1:使用组合() + abs() + 循环

在这种情况下,使用组合()提取所有可能的对。然后使用循环遍历,使用 abs() 求差。

Python3
# Python3 code to demonstrate working of
# All elements difference in Set
# Using combinations + abs() + loop
from itertools import combinations
  
# initializing strings set
test_set = {1, 5, 2, 7, 3, 4, 10, 14}
  
# printing original string
print("The original set is : " + str(test_set))
  
# getting combinations
combos = combinations(test_set, 2)
  
res = set()
  
# adding differences in set
for x, y in combos:
    res.add(abs(x - y))
  
# printing result
print("All possible differences : " + str(res))


Python3
# Python3 code to demonstrate working of
# All elements difference in Set
# Using set comprehension + combinations() + abs()
from itertools import combinations
  
# initializing strings set
test_set = {1, 5, 2, 7, 3, 4, 10, 14}
  
# printing original string
print("The original set is : " + str(test_set))
  
# set comprehension providing consize solution
res = {abs(x - y) for x, y in combinations(test_set, 2)}
  
# printing result
print("All possible differences : " + str(res))


输出:

方法#2:使用集合推导+组合()+abs()

在这种情况下,我们使用集合理解作为一种线性方法来执行获取和设置所有元素的任务来解决问题。

蟒蛇3

# Python3 code to demonstrate working of
# All elements difference in Set
# Using set comprehension + combinations() + abs()
from itertools import combinations
  
# initializing strings set
test_set = {1, 5, 2, 7, 3, 4, 10, 14}
  
# printing original string
print("The original set is : " + str(test_set))
  
# set comprehension providing consize solution
res = {abs(x - y) for x, y in combinations(test_set, 2)}
  
# printing result
print("All possible differences : " + str(res))

输出: