It may be a rudimentary mistake, but could someone please tell me...
The following code ↓
class Set:
def__init__(self, value=[]):
self.data = [ ]
self.concat(value)
def intersect (self, other):
res = [ ]
for x in self.data:
if x in other:
res.append(x)
return Set(res)
defunion(self, other):
res=self.data[:]
for x in other:
if not x in res:
res.append(x)
return Set(res)
def concat(self, value):
for x in value:
if not x in self.data:
self.data.append(x)
def__len__(self):returnlen(self.data)
def__getitem__(self, key):return self.data [key]
def__and__(self, other):return self.intersect(other)
def__or__(self, other): return self.union(other)
def__repr__(self):return'Set:'+`self.data`
After writing ↓
>>>x=Set ([1, 2, 3, 4])
and ↓
Traceback (most recent call last):
File", line 1, in
x = Set ([1, 2, 3, 4])
File "", line 4, in init
self.concat(value)
AttributeError: Set instance has no attribute 'concat'
appears.
I think the error is that I don't have a concat as an attribute, but I would like you to tell me how to deal with this case or if there is a defect in the code.
Thank you for your cooperation.
Python recognizes blocks by indentation.
Therefore, assuming that def concat
or the like is the Set method, it will not work unless one hierarchy is indented below class Set:
.
By the way, if x not in res
is the correct notation.
class Set:
def__init__(self, value=[]):
self.data = [ ]
self.concat(value)
def intersect (self, other):
res = [ ]
for x in self.data:
if x in other:
res.append(x)
return Set(res)
defunion(self, other):
res=self.data[:]
for x in other:
if x not in res:
res.append(x)
return Set(res)
def concat(self, value):
for x in value:
if x not in self.data:
self.data.append(x)
def__len__(self):
return len(self.data)
def__getitem__(self, key):
return self.data [key]
def__and__(self, other):
return self.intersect (other)
def__or__(self, other):
return self.union(other)
def__repr__(self):
return'Set:'+str(self.data)
if__name__=="__main__":
x = Set ([1, 2, 3, 4])
print(x)
The concat exists outside the class, so it does not work.Self is not required.
concat(self, value)
© 2024 OneMinuteCode. All rights reserved.