1. Engineering
  2. Computer Science
  3. before you implement the add operator i want you to...

Question: before you implement the add operator i want you to...

Question details

Before you implement the add operator, I want you to think about this scenerio a bit. Add combines two grocery lists into a new GroceryList. Seems like it can be a simple operation with two grocery lists, you just take the items in one list and combine them with the second list and return a new Grocery List that has both objects. Lets take a look at that behavior. Lets see what happens to newList when we modify one of the original lists. What is going on in memory here? Notice how making a modification to secondList that the related objects in newList also changed. >> firstList-GroceryList ) >>> firstList. readLǐstFromFile ( gr. txt ) True >>>secondList-GroceryList) >>> secondLǐst. readListFromFile ( gr. txt ) True >>>secondList.multiplyAllItemsCount (2) True >>> newList = firstList + secondList >>> print (str (newList)) milk:1.59:10:dairy eggs:1.99:2:dairy butter:1.99:1: dairy beef:8.99:1:meat milk:1.59:20:dairy eggs:1.99:4:dairy butter:1.99:2:dairy beef:8.99:2:meat 2 >>> #notice the counts above of the new list >>> #now go back to the second list and double the items aga >>> secondList.multiplyAllItemsCount (2) True >>> #look at the counts of the newlist
>>> #look at the counts of the newlist >>> print (str (newList)) milk:1.59:10:dairy eggs:1.99:2:dairy butter:1.99:1:dairy beef: 8.99:1:meat milk:1.59:40:dairy eggs: 1.99:8:dairy butter:1.99:4:dairy beef:8.99:4:meat >>> #why did they change and how can we prevent itd In the next version of the add operator that I wrote, notice modifying one of the original grocery lists does not modify the items in the new grocery list. I think this is more desireable behavior. How can you implement this? Hint: How can you make a copy of the
>>> firstList=Groce ryList () >>> firstlist.readListFromFile (gr.txt) True >> secondlist-GroceryList) >>> secondList.readListFromFile (gr.txt) True >>> secondList.multiplyAllitemsCount (2) True >>> newList = firstList + secondList >>> print (str (newList)) milk:1.59:10:dairy eggs: 1.99:2: dairy butter:1.99:1:dairy beef:8.99:1: meat milk: 1.59:20:dairy eggs: 1.99:4:dairy butter:1.99:2:dairy beef:8.99:2:meat >>> secondList.multiplyAllItemsCount (2) True >>> print (str (newList)) milk:1.59:10:dairy eggs: 1.99:2:dairy butter:1.99:1:dairy beef:8.99:1:meat milk:1.59:20:dairy eggs: 1.99:4:dairy butter:1.99:2:dairy beef: 8.99:2:meat
Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution