teacher assigned out of the book "python programming: an introduction to computer science. second edition. page 384 # 19 is as follows

this below is verbatim from the book and the instructions for the assignment are

"Python Assignment #10

Complete programming exercise #19 on page 384 from Chapter 11"

create and test a Set class to represent a classical set. your sets should support the following methods:

Set(elements): Create a set (elements is the initial list of items in the set)

addElement(x): Adds x to the set.

deleteElement(x): Removes x from the set if present. if x is not in the set, the set is left unchanged.

member(x): Returns true if x is in the set and false otherwise.

intersection(set2): Returns a new set containing just those elements that are common to this set, set2 or both

union(set2): Returns a new set containing all of elements that are in this set, set2, or both.

subtract(set2): Returns a new set containing all the elements of this set that are not in set2.

ive been really having a hard time, but have managed to come up with the below code...it runs and prints in idle, but when i type anything it gives me an error!im using python. thanks again for any help!

# class set declaration

class Set:

#initializing the set

def __init__(self, list1=[]):

self.list1 = list1

#adding the element to the set

def addElement(self, x):

if x not in self.list1:

self.list1.append(x)

return True

else:

return False

#deleting element from the set

def deleteElement(self, x):

if x in self.list1:

self.list1.remove(x)

return True

else:

return False

#check the element is in the set or not

def member(self, x):

if x in self.list1:

return True

else:

return False

#finding the union of the two sets

# the result is stored in new set and has no impact

#on original set

def union(self, aSet2=[]):

self.list2 = aSet2

newSetUnion = Set([])

for i in self.list1:

newSetUnion.addElement(i)

for j in self.list2:

if not j in self.list1:

newSetUnion.addElement(j)

return newSetUnion

#finding the intersection of the two sets

# the result is stored in new set and has no impact

#on original set

def intersection(self, aSet1=[]):

self.list3 = aSet1

newSetInter = Set([])

for i in self.list1:

if i in self.list3:

newSetInter.addElement(i)

return newSetInter

#finding the substraction of the two sets

# the result is stored in new set and has no impact

#on original set

def subtract(self, aSet3=[]):

self.list4 = aSet3

newSetSubtract = Set([])

for i in self.list1:

if i not in self.list4:

newSetSubtract.addElement(i)

return newSetSubtract

#to display the set

def displya(self):

return self.list1

def __str__(self):

return "%s" % self.list1

#main function

def main(self):

s = Set([0, 1, 2, 3, 4])

print

"The elements in the set are : ",

# Ask the user to enter the element to be added

n = input('Enter the element to add to the set: ')

#calling method to add the element

valid = s.addElement(n)

if valid == True:

print

"Element added to the set."

now = s.displya()

print

"Now the elements in the set are : ", now

print

"Element can not be added to the set."

# Ask the user to enter the element to be deleted

n = input("Enter the element to delete from the set: ")

#calling method to delete the element

valid = s.deleteElement(n)

if valid == True:

print

"Element deleted from the set."

now = s.displya()

print

"Now the elements in the set are : ", now

print

"Element not present in the set."

# Ask the user to enter the element to check

n = input("Enter the element to check in the set: ")

#calling method to check the element in the set

valid = s.member(n)

if valid == True:

print

"Element is in the set."

print

"Element not present in the set."

#calling the method to find union of two sets

now = s.union([5, 6, 7, 8])

print

"The result after Union with set [5,6,7,8] is : ", now

#calling the method to find intersection of two sets

now = s.intersection([2, 3])

print

"The result after Intersection with set [2,3] is : ", now

#calling the method to find subtraction of two sets

now = s.subtract([2, 3])

print

"The result after Subtraction with set [2,3] is : ", now

 main()

Recommended Answers

All 4 Replies

What is the error? Copy and paste the stacktrace/output. Also, formatting your code would help you get an answer. It makes it much easier to spot simple errors. Use the "</> Code" button, and paste your code there, or just make sure it is all indented with 4 spaces.

thanks for the help, the first error is "line 4, in <module>
    "class Set:" the second is "line 85, in Set
    valid = s.addElement(n)
NameError: name 's' is not defined"
# class set declaration


class Set:
    #initializing the set
    def __init__(self, list1=[]):
        self.list1 = list1

    #adding the element to the set
    def addElement(self, x):
        if x not in self.list1:
            self.list1.append(x)
            return True
        else:
            return False

    #deleting element from the set
    def deleteElement(self, x):
        if x in self.list1:
            self.list1.remove(x)
            return True
        else:
            return False

    #check the element is in the set or not
    def member(self, x):
        if x in self.list1:
            return True
        else:
            return False

    #finding the union of the two sets
    # the result is stored in new set and has no impact
    #on original set
    def union(self, aSet2=[]):
        self.list2 = aSet2
        newSetUnion = Set([])
        for i in self.list1:
            newSetUnion.addElement(i)
        for j in self.list2:
            if not j in self.list1:
                newSetUnion.addElement(j)
        return newSetUnion

    #finding the intersection of the two sets
    # the result is stored in new set and has no impact
    #on original set
    def intersection(self, aSet1=[]):
        self.list3 = aSet1
        newSetInter = Set([])
        for i in self.list1:
            if i in self.list3:
                newSetInter.addElement(i)
        return newSetInter

    #finding the substraction of the two sets
    # the result is stored in new set and has no impact
    #on original set
    def subtract(self, aSet3=[]):
        self.list4 = aSet3
        newSetSubtract = Set([])
        for i in self.list1:
            if i not in self.list4:
                newSetSubtract.addElement(i)
        return newSetSubtract

    #to display the set
    def displya(self):
        return self.list1

    def __str__(self):
        return "%s" % self.list1

    #main function
    def main(self):

        s = Set([0, 1, 2, 3, 4])
    print
    "The elements in the set are : ",

# Ask the user to enter the element to be added
    n = input('Enter the element to add to the set: ')

    #calling method to add the element
    valid = s.addElement(n)
    if valid == True:


     print
    "Element added to the set."
    now = s.displya()
    print
    "Now the elements in the set are : ", now
    print
    "Element can not be added to the set."

    # Ask the user to enter the element to be deleted
    n = input("Enter the element to delete from the set: ")

    #calling method to delete the element
    valid = s.deleteElement(n)
    if valid == True:
        print
    "Element deleted from the set."
    now = s.displya()
    print
    "Now the elements in the set are : ", now
    print

    "Element not present in the set."

    # Ask the user to enter the element to check
    n = input("Enter the element to check in the set: ")

    #calling method to check the element in the set
    valid = s.member(n)
    if valid == True:
       print
    "Element is in the set."

    print
    "Element not present in the set."

    #calling the method to find union of two sets
    now = s.union([5, 6, 7, 8])
    print
    "The result after Union with set [5,6,7,8] is : ", now

    #calling the method to find intersection of two sets
    now = s.intersection([2, 3])
    print
    "The result after Intersection with set [2,3] is : ", now

    #calling the method to find subtraction of two sets
    now = s.subtract([2, 3])
    print
    "The result after Subtraction with set [2,3] is : ", now

main()

Indention level matters in Python. I see you assign s in main(), but the code following that is actually outside of main() because of it's indention level. In other words, this:

#main function
def main(self):

    s = Set([0, 1, 2, 3, 4])
print
"The elements in the set are : ",

# Ask the user to enter the element to be added
n = input('Enter the element to add to the set: ')

#calling method to add the element
valid = s.addElement(n)
# ... All code for main() below this too..

Needs to be this:

#main function
def main(self):
    s = Set([0, 1, 2, 3, 4])
    print "The elements in the set are : ",

    # Ask the user to enter the element to be added
    n = input('Enter the element to add to the set: ')

    #calling method to add the element
    valid = s.addElement(n)
    # ... All code for main() below this too..

So you were accessing s before main() was even called (during definition on file load). Also notice how I put the print statement all on one line. This will print a blank line:

print
"Hello",

This will print "Hello " (a space is added because of the ,):

print "Hello",

When you separate the lines like that, "Hello", is not part of the print statement. It is evaluated and the result is thrown away. print statements should be on the same line, or if you really have to break them up you can do something like this:

print (
    "My first line.\n"
    "My second line."
    )

Which python automatically converts to this:

print ("My first line.\n" + "My second line.")

Although, when concatenating strings you may want to look at str.join(), as in:

print '\n'.join(('My first line.', 'My second line.'))

See Python's PEP 8 Style Guide for tips on how to format your code for readability and compatibility with other people. Also, see from __future__ import print_function to bring Python 3's print function into Python 2.

Example of code that runs but doesn't do anything:

print
"This may as well be a comment."
"May as well have done this:"
print
2 + 2 # The result is thrown away.

This would print 2 blank lines and exit, when what you really wanted was this:

print "This is no longer a comment."
# This will work too:
print (2 + 2)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.