objects not working right: attribute error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Monty27
    New Member
    • Nov 2011
    • 1

    objects not working right: attribute error

    I am completely stuck and am looking for guidance. I am creating my own version of the sets class, making the class called Set. I have created a test function as well. Everything works great until I get to the union/subtract part.
    Code:
    def intersection(self,set2):
            self.inter=Set([])
            for i in self.elements:
                for j in set2.elements:
                    if i == j:
                        self.inter = self.inter.addElement(j)
            return self.inter
            
        def union(self,set2):
            self.un=Set([])
            for i in self.elements:
                self.un = self.un.addElement(i)
                for j in set2.elements:
                    if i!=j:
                        self.un = self.un.addElement(j)
            return self.un
    
        def subtract(self,set2):
            self.sub=Set([])
            for i in self.elements:
                self.sub= self.sub.addElement(i)
                for j in set2.elements:
                    if i==j:
                        self.sub= self.sub.deleteElement(i)
            return self.sub
    Now, intersection works fine. I basically was following the same pattern for union, but when I run it...

    Code:
    Traceback (most recent call last):
      File "C:\Users\monty27\Desktop\Math Computing\setsMontgomery.py", line 87, in <module>
        main()
      File "C:\Users\monty27\Desktop\Math Computing\setsMontgomery.py", line 83, in main
        print "Union:", set1.union(set2)
      File "C:\Users\monty27\Desktop\Math Computing\setsMontgomery.py", line 39, in union
        self.un = self.un.addElement(j)
    AttributeError: 'list' object has no attribute 'addElement'
    Thoughts? I've messed around with this quite a bit, trying to just copy self.elements and then verbatim use the intersection() code with the exception of making the if statement i!=j. It just does not work.
    Last edited by bvdet; Nov 25 '11, 03:04 PM. Reason: edit comments
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    This may or may not help, but the logic is wrong for intersection. You're adding all the elements of set2 multiple times. Basically for each i you add all the elements of set2 that are not equal to i (which is all of them or all of them except 1).

    This is I suppose an issue since you appear to be going to quite a bit of effort to ensure that addElement only adds new elements.

    If this is indeed the issue, I would consider making addElement itself more robust. So when you add an element, check if it's in there already and only add it if not.

    Let me know if that helps. If not, please post the addElement method.

    Comment

    Working...