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
  • 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...

  • create a class named IntegerQueue given a singlylinkedqueue of integers, write the following methods: max(SinglyLinkedQueue<Integer> s)...

    create a class named IntegerQueue given a singlylinkedqueue of integers, write the following methods: max(SinglyLinkedQueue<Integer> s) to return the max element in the queu. min(SinglyLinkedQueue<Integer> s) to return the min element in the queue. sum(SinglyLInkedQueue<Integer> s) to return the sum of elements in the queu. median(SinglyLinkedQueue<Integer> s) to return the median of elements in the queue. split(SinglyLinkedQueue<Integer> s) to separate the SinglyLinkedQueue into two ArrayQueues based on whether the element values are even or odd. package Stack_and_Queue; import java.util.Iterator; import...

  • Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

    Python 3: Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list...

  • 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...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display,...

    Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display, remove methods. You may use default arguments and/or helper functions. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list """ if self.head is...

  • Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - ...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. - parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None - leftChild(index) returns the value of the left child of heap[index], returns None if there is no value - rightChild(index) returns...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • python * important *

    In this question, you will complete the FootballPlayer class, which is used to  compute some features of a Football Player. The class should be constructed with the name and age, as well as shooting, passing, tackling and saving skill  points of a player. The constructor method as well as the defenderScore method  is provided below. You should implement the remaining methods. The definitons  of the methods are presented below as comments.  An example execution and the corresponding outputs are provided below: >>> burkay = FootballPlayer("Burkay", 42, 15, 30, 10, 15) >>> cemil = FootballPlayer("Cemil", 30, 70, 30, 45, 20) >>> ronaldo = FootballPlayer("Ronaldo", 36, 85, 95, 35, 5) >>> print(burkay) (Burkay,42,13640000) >>> print(cemil) (Cemil,30,144270000) >>> print(ronaldo) (Ronaldo,36,322445000) >>> print(burkay > cemil) False >>> print(ronaldo > burkay) True """ class FootballPlayer:     def __init__(self, na, ag, sh, pa, ta, sa):         # age is in [18,40]         # skills are in [10,100]         self.name = na         self.age = ag         self.shooting = sh         self.passing = pa         self.tackling = ta         self.saving = sa     def defenderScore(self):         # The defensive score is defined as 80% tackling, 15% passing and 5% shooting         # It should be reported as integer         return int(0.80 * self.tackling + 0.15 * self.passing + 0.05 * self.shooting)     def midfielderScore(self):         # The midfielder score is defined as 50% passing, 25% shooting and 25% tackling         # It should be reported as integer         return # Remove this line to answer this question     def forwardScore(self):         # The forward score is defined as 70% shooting, 25% passing and 5% tackling         # It should be reported as integer         return # Remove this line to answer this question     def goalieScore(self):         # The goalie score is defined as 90% saving and 10% passing         # It should be reported as integer         return # Remove this line to answer this question     def playerValue(self):         # Player value is defined as          # * 15000$ per unit of the square of defensive score         # * 25000$ per unit of the square of midfielder score         # * 20000$ per unit of the square of forward score         # * 5000$ per unit of the square of goalie score         # * -30000$ per (age-26)^2         # A player's value is never reported as negative. The minimum is 0.         # It should be reported as integer         return # Remove this line to answer this question     def __str__(self):         # This method returns a string representation of the player, such as         # "(name,age,playerValue)"         return # Remove this line to answer this question     def __gt__(self, other):         # This method returns True if the player value of self is greater than          # the player value of other. Otherwise, it returns False.         return # Remove this line to answer this question

  • ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value):...

    ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value): self.value = value self.next = None def __repr__(self): return "{}".format(self.value) def __init__(self): self.top = None def shuffle(self): card_list = 4 * [x for x in range(2, 12)] + 12 * [10] random.shuffle(card_list) self.top = None for card in card_list: new_card = self.Card(card) new_card.next = self.top self.top = new_card def __repr__(self): curr = self.top out = "" card_list = [] while curr is not None:...

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
ADVERTISEMENT