Question

Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() :...

Python 3+

Adjust the following code so the two errors below are non-present:

1. __init__() : Since Pizza object don't have it's own set() datastructure, the toppings in the pizza object are manimupated from out of the object. (-1.0)
2. __eq__() : How about "self.toppings == other.toppings" rather than "self.toppings - other.toppin == set())".

Code:

## Program 1
## ---------------------------------

class Pizza:
def __init__(self, s='M', top=set()):
self.setSize(s)
self.toppings = top

def setSize(self, s):
self.size = s

def getSize(self):
return self.size

def addTopping(self, top):
self.toppings.add(top)

def removeTopping(self, top):
self.toppings.remove(top)

def price(self):
if self.size == 'S':
return 6.25 + (0.7 * len(self.toppings))
elif self.size == 'M':
return 9.95 + (1.45 * len(self.toppings))
else:
return 12.95 + (1.85 * len(self.toppings))

def __repr__(self):
end = 'Pizza('
end += ('\'' + self.size + '\'')
end += ','
end += str(self.toppings)
end += ')'
return end

def __eq__(self, other):
return self.size == other.size and (self.toppings - other.toppings == set ())


## Program 2
## ---------------------------------


def orderPizza():
print('Welcome to Python Pizza!')
size = input('What size pizza would you like (S,M,L): ')
za = Pizza(size, set())
while True:
topping = input('Type topping to add (or Enter to quit): ')
if topping == '':
break
else:
za.addTopping(topping)
print('Thanks for ordering!')
print('Your pizza costs $' + str(za.price()))
return za

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

CODE

==============

## Program 1

## ---------------------------------

class Pizza:

def __init__(self, s='M', top=set()):

self.setSize(s)

self.toppings = top

def setSize(self, s):

self.size = s

def getSize(self):

return self.size

def addTopping(self, top):

self.toppings.add(top)

def removeTopping(self, top):

self.toppings.remove(top)

def price(self):

if self.size == 'S':

return 6.25 + (0.7 * len(self.toppings))

elif self.size == 'M':

return 9.95 + (1.45 * len(self.toppings))

else:

return 12.95 + (1.85 * len(self.toppings))

def __repr__(self):

end = 'Pizza('

end += (''' + self.size + ''')

end += ','

end += str(self.toppings)

end += ')'

return end

def __eq__(self, other):

return self.size == other.getSize() and (self.toppings == other.toppings)


## Program 2

## ---------------------------------


def orderPizza():

print('Welcome to Python Pizza!')

size = input('What size pizza would you like (S,M,L): ')

za = Pizza(size, set())

while True:

topping = input('Type topping to add (or Enter to quit): ')

if topping == '':

break

else:

za.addTopping(topping)

print('Thanks for ordering!')

print('Your pizza costs $' + str(za.price()))

return za

pizza1 = orderPizza()

pizza2 = orderPizza()

print(pizza1 == pizza2)

Add a comment
Answer #2
  1. Regarding the init() method: The statement "Since Pizza object doesn't have its own set() data structure, the toppings in the pizza object are manipulated from outside the object" is incorrect. The Pizza object does have its own set() data structure for storing the toppings, and the toppings are manipulated within the object itself. The line self.toppings = top in the init() method initializes the toppings attribute of the Pizza object with the provided set of toppings.

  2. Regarding the eq() method: You are correct that a simpler and more direct way to compare the toppings of two Pizza objects is by using self.toppings == other.toppings instead of self.toppings - other.toppings == set(). The equality check self.toppings == other.toppings compares the sets directly to determine if they contain the same elements. The expression self.toppings - other.toppings == set() checks if the set difference between the two toppings sets is an empty set, indicating that they have the same elements.

Using self.toppings == other.toppings is a clearer and more concise way to express the intention of comparing the toppings. The modified eq() method would be as follows:

pythonCopy codedef __eq__(self, other):    return self.size == other.size and self.toppings == other.toppings

This updated implementation directly compares the sizes and toppings of the two Pizza objects, ensuring that both attributes match for the objects to be considered equal.


answered by: Mayre Yıldırım
Add a comment
Know the answer?
Add Answer to:
Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() :...
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
  • USE!! PYTHON!!! Programming:   Pizza 1. Write a Pizza class to that this client code works. Please...

    USE!! PYTHON!!! Programming:   Pizza 1. Write a Pizza class to that this client code works. Please note that it is ok if the toppings are listed in a different order. >>> pie = Pizza() >>> pie Pizza('M',set()) >>> pie.setSize('L') >>> pie.getSize() 'L' >>>pie.addTopping('pepperoni') >>>pie.addTopping('anchovies') >>>pie.addTopping('mushrooms') >>> pie Pizza('L',{'anchovies', 'mushrooms', 'pepperoni'}) >>>pie.addTopping('pepperoni') >>> pie Pizza('L',{'anchovies', 'mushrooms', 'pepperoni'}) >>>pie.removeTopping('anchovies') >>> pie Pizza('L',{'mushrooms', 'pepperoni'}) >>> pie.price() 16.65 >>> pie2 = Pizza('L',{'mushrooms','pepperoni'}) >>> pie2 Pizza('L',{'mushrooms', 'pepperoni'}) >>> pie==pie2 True The Pizza class should have...

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

  • 9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name,...

    9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name, age) + getName + getAge0 def init (self, name, age): self.mName = name self.mAge = age Dog Cat def getName(self): return self.mName mSize mColor + __init__(name, age,size) + getSize() + momCommento + getDog Years() +_init__(name, age,color) + getColor + pretty Factor + getCatYears def getAge(self): return self.mAge #dog.py import pet #cat.py import pet class Dog (pet. Pet): class Cat (pet. Pet): def init (self,...

  • Page 3 of 7 (Python) For each substring in the input string t that matches the...

    Page 3 of 7 (Python) For each substring in the input string t that matches the regular expression r, the method call re. aub (r, o, t) substitutes the matching substring with the string a. Wwhat is the output? import re print (re.aub (r"l+\d+ " , "$, "be+345jk3726-45+9xyz")) a. "be$jk3726-455xyz" c. "bejkxyz" 9. b. "be$jks-$$xyz" d. $$$" A object a- A (2) 10. (Python) What is the output? # Source code file: A.py class A init (self, the x): self.x-...

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

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

  • COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

    COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild): self.value, self.lchild, self.rchild = value, lchild, rchild def __init__(self): self.treeRoot = None    #utility functions for constructTree def mask(self, s): nestLevel = 0 masked = list(s) for i in range(len(s)): if s[i]==")": nestLevel -=1 elif s[i]=="(": nestLevel += 1 if nestLevel>0 and not (s[i]=="(" and nestLevel==1): masked[i]=" " return "".join(masked) def isNumber(self, expr): mys=s.strip() if len(mys)==0 or not isinstance(mys, str): print("type mismatch error: isNumber")...

  • Need help the first picture is the code I have so far the second are the...

    Need help the first picture is the code I have so far the second are the requirements. It’s a deque array in python class dequeArray: DEFAULT-CAPACITY 10 #moderate capacity for all new queues def init (self): self.capacity-5 capacity self.capacity self.data self, make array(self. capacity) self. size self. front-θ def len (self): return self. size def _getiten-(self, k); #Return element at index k if not θ k < self. size: raise IndexError('invalid index) return self._data[k] def isEmpty(self): if self. data0: return...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

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