Question

For python In this chapter, we implemented the Set ADT using a list. Implement the Set...

For python In this chapter, we implemented the Set ADT using a list. Implement the Set ADT using a bag created from the Bag class. In your opinion, which is the better implementation? Explain your answer.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
from collections import defaultdict
from goody import type_as_str
import copy
from collections import Counter

class Bag:

     def __init__(self, items = []):
         self.bag_value = defaultdict(int)
         for item in items:
             self.bag_value[item] += 1


     def __repr__(self):
         bag_list = []
         for item, count in self.bag_value.items():
             bag_list.extend(list(item*count))
         return 'Bag(' + str(bag_list) + ')'



     def __str__(self):
         return 'Bag(' + ','.join(str(item) + '[' + str(count) + ']' for item, count in self.bag_value.items()) + ')'



     def __len__(self):
         bag_len = 0
         for value in self.bag_value:
             bag_len += self.bag_value[value]
         return bag_len



     def unique(self):
         return len(self.bag_value)




      def __contains__(self, item):
          return item in self.bag_value



      def count(self, item):
          if item in self.bag_value:
             return self.bag_value[item]
          else:
             return 0



      def add(self, new):
          self.bag_value[new] += 1



      def __add__(self,right):
          mergedbag = Bag()
          mergedbag.bag_value = copy.copy(self.bag_value)
          for item in right.bag_value.keys():
              mergedbag.bag_value[item] += right.bag_value[item]
          return mergedbag



      def remove(self, item):
          if item in self.bag_value:
              if self.bag_value[item] == 1:
                  del self.bag_value[item]
              else:
                  self.bag_value[item] -= 1
          else:
              raise ValueError(str(item) + ' not in bag')



      def __eq__(self, right):
          if type(right) is not Bag:
              raise TypeError('Cannot compare Bag with' + type_as_str(right) + '. Can only compare Bag with Bag')
          else:
              return (Counter(self.bag_value)==Counter(right))



      def __ne__(self, right):
          return not self.__eq__(right)



      def __generate__(self, bag_value):
          for item in self.bag_value:
              for value in range(self.bag_value[item]):
                  yield item



      def __iter__(self):
          return self.__generate__(self.bag_value)




if __name__ == '__main__':
#     bag = Bag(['d','a','b','d','c','b','d'])
#     bag2 = Bag(['d','a','b','d','c','b','d'])
#     bag3 = Bag(['d','a','b','d','c','b'])
#     print(bag == bag2)
#     print(bag == bag3)
#     print(bag != bag2)
#     print(bag != bag3)
    import driver
    driver.driver()
Add a comment
Know the answer?
Add Answer to:
For python In this chapter, we implemented the Set ADT using a list. Implement the Set...
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
  • In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the...

    In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the element of the heap with the smallest key is the root of the binary tree. On the other hand, a max-heap has as root the element with the biggest key, and the relationship between the keys of a node and its parent is reversed of that of a min-heap. We also discussed an array-based implementation of heaps. In this assignment, your task is to...

  • Chapter 4 describes the ADT Sorted List using an array implementation with a maximum of 25...

    Chapter 4 describes the ADT Sorted List using an array implementation with a maximum of 25 items. The pseudocode for the ADT Sorted List Operations are provided on page 210. Use this information to create an ADT for handling a collection of Person objects, where each object will contain a Social Insurance Number (validate this), a first name, a last name, a gender and a data of birth. This implementation should prevent duplicate entries – that is, the Social Insurance...

  • Using a doubly linked list as the underlying data structure, implement a list ADT that implements...

    Using a doubly linked list as the underlying data structure, implement a list ADT that implements the ListInterface.java found in the ProgProjTwo Eclipse project starting point for this assignment. In addition to the forward iterator defined by resetIterator( ) and getNextItem( ) in ListInterface.java, implement a backwards iterator by providing resetBackIterator( ) and getPreviousItem( ) methods. As noted in the syllabus addendum, you are encouraged to develop a find( ) helper method that can support various list ADT operations. A...

  • The ADT Bag is a group of items, much like what you might have with a...

    The ADT Bag is a group of items, much like what you might have with a bag of groceries. In a software development cycle, specification, design, implementation, test/debug, and documentation are typical activities. The details are provided in the rest of the document. ADT Bag Specification: (Note: You should not change the names of the operations in your program. This should be included in an interface.) Specify operations to  create an empty bag that can hold up to 100...

  • please answer all questions thanks Question 21 Not yet In a linked-node implementation of a ADT,...

    please answer all questions thanks Question 21 Not yet In a linked-node implementation of a ADT, node does not reference the data in another node answered Points out of 2.00 Select one: True P Flag question False Question 23 Not yet An array implementation of an ADT potentially wastes more space than a linked implementation answered Points out of 2.00 Select one: True P Flag question False Question 25 Should Node be a public class? Briefly explain Not yet answered...

  • Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT....

    Please help with this Java Program. Thank you! we will be implementing an Ordered List ADT. Our goal is to implement the interface that is provided for this ADT. Notice that there are two interfaces: OrderedListADT builds on ListADT. In this homework, you'll only be responsible for the OrderedListADT. Figure 1: UML Overview 1 Requirements Create a doubly linked implementation of the OrderedListADT interface. Note that the book includes most of the source code for a singly linked implementation of...

  • When using an array to implement a list ADT, what is the time complexity (Big-Oh) for...

    When using an array to implement a list ADT, what is the time complexity (Big-Oh) for finding an element in the list with N elements? (C++)

  • Homework #1 – Implementing Set with a Linked List Project Objectives 1. Be able to integrate...

    Homework #1 – Implementing Set with a Linked List Project Objectives 1. Be able to integrate the knowledge of Java Generics, Collection Framework and the Linked List data structure to implement the Set ADT. Components emphasized are: • Allowing parameterized type for handling a general class of values in the collection framework; • Understanding conceptual differences between lists and sets and implementing them with methods; • Implementation of an iterator with functionality that is appropriate for the collection, namely the...

  • JAVA coding The Sorted List ADT Implement the SortedList class. The SortedList class extends the ...

    JAVA coding The Sorted List ADT Implement the SortedList class. The SortedList class extends the AbstractList class. Both can be seen here. Your assignment is to implement (recursively) all of the abstract methods of the AbstractList class. They are: insert (recursive) iterator remove (recursive) retrieve search (recursive) You must also implement an Iterator inner class for the SortedList class. You must submit a modified SortedList.java file with your source code. Do not submit and do not modify the List.java or...

  • Multiple Choice Multiple Choice Section 3.1 The Bag ADT For the bag class in Chapter 3...

    Multiple Choice Multiple Choice Section 3.1 The Bag ADT For the bag class in Chapter 3 (using a fixed array and a typedef statement) what steps were necessary for changing from a bag of integers to a bag of double values? A. Change the array declaration from int data[CAPACITY] to double data[CAPACITY] and recompile. B. Change the int to double in the typedef statement and recompile. C. Round each double value to an integer before putting it in the bag....

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