[英]How to pass 2 sets as parameters for a function?
創建一個Python程序,要求用戶輸入兩組以逗號分隔的值。 使用字符串split()
方法解析該行,然后使用set()函數隱蔽要設置的列表。 通過將兩個集合及其彼此的關系顯示為子集,超集,並集,交集和差來論證兩個集合的集理論。
我不確定如何在函數中傳遞兩個集合?
print(two_set(set(1,2,3,4), set(2,3,4,5,6)))
TypeError:設置期望的最多1個參數,得到4個
您應該將其轉換為set
,然后將其傳遞:
def two_set(set_a, set_b):
return (set_a, set_b)
set_a = set([1,2,3,4])
set_b = set([2,3,4,5,6,6,6,6])
print(two_set(set_a, set_b))
輸出:
({1, 2, 3, 4}, {2, 3, 4, 5, 6})
這是解決方案之一。
class Settherory:
def __init__(self, set1,set2):
self.set1 = set1
self.set2=set2
def subset(self):
if self.set1.issubset(self.set2):
return '{} is subset of {}'.format(self.set1,self.set2)
elif self.set2.issubset(self.set1):
return '{} is subset of {}'.format(self.set2,self.set1)
else:
return 'not a subset'
def superset(self):
if self.set1.issuperset(self.set2):
return '{} is superset of {}'.format(self.set1,self.set2)
elif self.set2.issuperset(self.set1):
return '{} is superset of {}'.format(self.set2,self.set1)
else:
return 'not a superset'
def union(self):
return 'union of sets is {}'.format(self.set1 | self.set2)
def difference(self):
return 'difference of set is {}'.format(self.set1 - self.set2)
def intersection(self):
return 'intersection of two sets is {}'.format(self.set1 & self.set2)
set_1 = set(map(int,input('enter the data in set 1 ').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2').strip().split(',')))
x= Settherory(set_1, set_2)
print(x.subset(), x.difference(), x.superset(),x.union(),x.intersection(),sep='\n')
'''
enter the data in set 1 1,2,3,4,5
enter the data in set 23,4,5
{3, 4, 5} is subset of {1, 2, 3, 4, 5}
difference of set is {1, 2}
{1, 2, 3, 4, 5} is superset of {3, 4, 5}
union of sets is {1, 2, 3, 4, 5}
intersection of two sets is {3, 4, 5}
'''
另一種方法是
# take input as single line seperated by ','
set_1 = set(map(int,input('enter the data in set 1 :').strip().split(',')))
set_2 = set(map(int,input('enter the data in set 2 : ').strip().split(',')))
# for finding the subset or other set operation you can use direct inbuilt function on set like:
print(set_1.issubset(set_2))
print(set_1.issuperset(set_2))
print(set_1.union(set_2))
print(set_1.difference(set_2))
# output
'''
enter the data in set 1 : 1,2,3,4
enter the data in set 2 : 2,3
False
True
{1, 2, 3, 4}
{1, 4}
'''
set類采用一個數組進行初始化,但是您提供了多個整數。 將您的代碼更改為
print(two_set(set([1,2,3,4]), set([2,3,4,5,6])))
解決你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.