Scientific Programming II

Programming in Python

Assignment 2


In a manner similar to the midterm assignment for Programming in Java, modify the class Set to have is_subset(other), union(other), and intersect(other) methods. You may refer back to the assignment for an explanation of these set functions.

The Set class and a link back to the midterm assignment are provided below:

Midterm Assignment

Set.py

class Set():
    def __init__(self):
        self.vals = []

    def __add__(self, other):
        if not isinstance(other, int):
            raise TypeError("Cannot add non-ints to sets")

        # Using 'in' and 'not in' will allow us to test if
        # some object is contained in a collection.
        if other not in self.vals:
            self.vals.append(other)
        return self

    def __radd__(self, other):
        if not isinstance(other, int):
            raise TypeError("Cannot add non-ints to sets")

        if other not in self.vals:
            self.vals = [other] + self.vals
        return self

    # We can give our custom classes the ability to use 'in'
    # and 'not in' with this magic method. Neat!
    def __contains__(self, item):
        return item in self.vals

    def __str__(self):
        return str(self.vals)