Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

bagDifference: The difference of two bags is a new bag containing the entries th

ID: 3872359 • Letter: B

Question

bagDifference: The difference of two bags is a new bag containing the entries that would be left in one bag after removing those that also occur in the second. Design and specify a method difference for the ArrayBag that returns as a new bag the difference of the bag receiving the call to the method and the bag that is the method's parameter. The method signature is:

ArrayBag bagDifference(const ArrayBag &otherBag) const;

Note that the difference of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the difference of these bags contains x three times.

Example run: https://i.imgur.com/4ee5TS9.png

Explanation / Answer

Python 2.7 code :

#function to find difference between two bags i.e (bag1 - bag2)
def difference(bag1, bag2):
for entry in bag2:
  if (entry in bag1):
   bag1.remove(entry)     # if entry which is present in bag2 is also present in bag1 then remove it
return bag1

bag1 = ["1", "2", "3", "4", "5"] # initizlise bag1
bag2 = ["20","30","40","50","1"] # initizlise bag2
print "First bag: the bag contains ", len(bag1), " items:"
for entry in bag1:
print entry,
print " "
print "Second bag: the bag contains ", len(bag2), " items:"
for entry in bag2:
print entry,
print " "
diff = difference(bag1,bag2)
print "The bag containing difference of these 2 bags contains ", len(diff), "items:"
for entry in diff:
print entry,

Sample Output:

First bag: the bag contains 5 items:
1 2 3 4 5

Second bag: the bag contains 5 items:
20 30 40 50 1

The bag containing difference of these 2 bags contains 4 items:
2 3 4 5