【发布时间】:2022-01-13 08:31:56
【问题描述】:
使用下面的代码:
class Int_set(list):
def __init__(self):
self.vals=[]
self.index=0
def insert(self, elm): #assume a string of numbers
for x in elm:
if x not in self.vals:
self.vals.append(int(x))
return self.vals
def member(self, elm):
return elm in self.vals
def remove(self, elm):
try:
self.vals.remove(elm)
except:
raise ValueError(str(elm)+' not found')
def get_members(self):
return self.vals[:]
def __str__(self):
if self.vals == []:
return '[]'
self.vals.sort()
result = ''
for e in self.vals:
result = result + str(e) + ','
return f'{{{result[:-1]}}}'
def union(self, other):
'''add all non-duplicate elements from other set to self set'''
print(len(other))
for e in range(len(other)):
if other[e] not in self.vals:
self.vals.append(other[e])
else:
continue
return self.vals
set1=Int_set()
set1.insert('123456')
print(set1.get_members())
set2=Int_set()
set2.insert('987')
print(set2.get_members())
print(set1.union(set2))
我得到输出:
[1, 2, 3, 4, 5, 6]
[9, 8, 7]
0 # the print(len(other)) in def union
[1, 2, 3, 4, 5, 6]
请注意,def union(self, other) 没有添加从 set2 到 set1 的所有唯一数字。但是,如果我使用:
print(set1.union(set2.vals))
然后我得到:
[1, 2, 3, 4, 5, 6]
[9, 8, 7]
3 # the print(len(other)) in def union
[1, 2, 3, 4, 5, 6, 9, 8, 7]
这是什么原因造成的?我假设.union(set2) 中的 set2 处于初始化时的状态(因此它是一个空列表)。但是我在里面插入了一些数字并打印出来
【问题讨论】:
-
你为什么不直接使用
set而不是上课??! -
您没有接受任何回答。没有一个答案能解决您的问题吗?您需要更多信息吗?