Reputation: 145
In this program, I noticed that when I used print to display the intersection of two sets, there is difference in the output, one formats according to __str__()
other just prints out the list. Why is it so ? Is it true for all the other python magic functions ? Sorry for such a long code.
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def intersect(self, other):
"""Input: two set of integers - sel and other
Returns intersection of the two sets.
"""
temp = self.vals[:]
for e in temp:
if e not in other.vals:
self.vals.remove(e)
return self.vals
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'
setA = intSet()
setA.insert(3)
setA.insert(4)
setA.insert(5)
setB = intSet()
setB.insert(6)
setB.insert(4)
setB.insert(8)
print("setA: ", setA)
print("setB: ", setB)
setA.intersect(setB)
print(setA) #output: {4}
print("setA.intersect(setB): ", setA.intersect(setB)) #output: [4]
Upvotes: 0
Views: 62
Reputation: 451
It's because the print(setA)
prints the intSet object instance and the print("setA.intersect(setB): ", setA.intersect(setB))
is printing the return value of the intersect method which is a list.
Upvotes: 2