Question

In Python

class int Set (object): An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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 __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'

def __len__(self):
"""Returns the number of elements in s."""
return len(self.vals)

def intersect(self,other):
""" Returns a new IntSet that contains of integers in both s1 & s2 """
commonSet = intSet()
#Note member is intSet interal Method
for x in self.vals:
if other.member(x):
commonSet.insert(x)
return commonSet


#Test Case
s1 = intSet()
s2 = intSet()
s1.insert(1)
s1.insert(2)
s1.insert(3)
s1.insert(4)
s2.insert(3)
s2.insert(4)
s2.insert(5)
s2.insert(6)
s2.insert(7)

print(s1)
print(s2)
print(s1.intersect(s2))
print(len(s1))

output

Command Prompt B:\Chegg\Python>py setClass . py {3,4,5,6,7} (3,4) 4 B: \Chegg\Python> 20:55 OType here to search ENG 29-07-20

code snaps

setClass.py- BChegg Python-Atom File Edit View Selection Find Packages Help setClass.py class intSet(object): An intSet is asetClass.py- B\Chegg Python-Atom File Edit View Selection Find Packages Help setClass.py def str_(self) : 28 29 Returns a stsetClass.pyBCheggPython-Atom File Edit View Selection Find Packages Help setClass.py intersect(self, other) : def auReturns n

If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.

Add a comment
Know the answer?
Add Answer to:
In Python class int Set (object): "" "An intSet is a set of integers The value...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write the C module intSet to implement an unordered set of integers according to the specification...

    Write the C module intSet to implement an unordered set of integers according to the specification given below. File intSet.h (downloadable off the class web pages): #ifndef INTSET_H #define INTSET_H typedef struct intsetType *intSet; intSet createSet(); // returns an intSet created at runtime using malloc void destroySet(intSet); // frees up the memory associated with its argument void clear(intSet); // clears set to empty (freeing any memory if necessary) int card(const intSet); // returns the cardinality of the set bool equals(const...

  • Write the C module intSet to implement an unordered set of integers according to the specification...

    Write the C module intSet to implement an unordered set of integers according to the specification given below. File intSet.h: #ifndef INTSET_H #define INTSET_H typedef struct intsetType *intSet; intSet createSet(); // returns an intSet created at runtime using malloc void destroySet(intSet); // frees up the memory associated with its argument void clear(intSet); // clears set to empty (freeing any memory if necessary) int card(const intSet); // returns the cardinality of the set bool equals(const intSet,const intSet); // returns true if...

  • Please code in Python Revise the AbstractBag class so that it behaves as a subclass of...

    Please code in Python Revise the AbstractBag class so that it behaves as a subclass of AbstractCollection provided in the file abstractcollection.py. Abstractcollection.py code: class AbstractCollection(object):     """An abstract collection implementation."""     # Constructor     def __init__(self, sourceCollection = None):         """Sets the initial state of self, which includes the         contents of sourceCollection, if it's present."""         self.size = 0         if sourceCollection:             for item in sourceCollection:                 self.add(item)     # Accessor methods     def isEmpty(self):         """Returns True if len(self) == 0, or False otherwise."""         return len(self) == 0...

  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • How do you do this? class Event: """A new calendar event.""" def __init__(self, start_time: int, end_time:...

    How do you do this? class Event: """A new calendar event.""" def __init__(self, start_time: int, end_time: int, event_name: str) -> None: """Initialize a new event that starts at start_time, ends at end_time, and is named name. Precondition: 0 <= start_time < end_time <= 23 >>> e = Event(12, 13, 'Lunch') >>> e.start_time 12 >>> e.end_time 13 >>> e.name 'Lunch' """    self.start_time = start_time self.end_time = end_time self.name = event_name def __str__(self) -> str: """Return a string representation of this...

  • In python class Customer: def __init__(self, customer_id, last_name, first_name, phone_number, address): self._customer_id = int(customer_id) self._last_name =...

    In python class Customer: def __init__(self, customer_id, last_name, first_name, phone_number, address): self._customer_id = int(customer_id) self._last_name = str(last_name) self._first_name = str(first_name) self._phone_number = str(phone_number) self._address = str(address) def display (self): return str(self._customer_id) + ", " + self._first_name + self._last_name + "\n" + self._phone_number + "\n" + self._address customer_one = Customer("694", "Abby", "Boat", "515-555-4289", "123 Bobby Rd", ) print(customer_one.display()) customer_two = Customer ("456AB", "Scott", "James", "515-875-3099", "23 Sesame Street Brooklyn, NY 11213") print(customer_two.display()) Use Customer class remove the address attribute.Place the code...

  • Create the abstract data type IntSet used to implement a mathematical set of non-negative integers (includes...

    Create the abstract data type IntSet used to implement a mathematical set of non-negative integers (includes zero). Each object of class IntSet can keep track of whether integers are in the set or not. Implement as follows. A set is to be represented internally as a bool array containing true and false. For example, if you call the array set, then set[num] is true if the integer num is in the set, false if num is not in the set....

  • #!/usr/bin/env python3 import array    # provides access to primitive arrays     def copy(self):         '''        ...

    #!/usr/bin/env python3 import array    # provides access to primitive arrays     def copy(self):         '''         this behaves like a copy constructor that makes a detailed copy of self         NOTE: the capacity of the copy matches the elements in self unless               the bag is empty, in which case it should be at least 1         Postcondition:             x.copy() is x returns false             type(x.copy()) == type(x)             x.copy() == x             internal capacity of copy is just enough...

  • In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...

    In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains, insert, and normal_list methods. You may use default arguments and/or helper functions. The file must be named: LinkedList.py Here is what I have for my code so far. The methods I need the recursive implementations for will be bolded: class Node: """ Represents a node in a linked list (parent class) """ def __init__(self, data): self.data = data self.next = None class LinkedList: """...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT