Bags data structure in python| explain bags data structure |

 Bags data structure in python| explain bags data structure |

Bags Data structure in python  –

A bag is a simple container like a shopping bag that can be used to store a collection of items. 

The bag container restricts access to the individual items by only defining operations for adding and removing individual items, for determining if an item is in the bag, and for traversing over the collection of items.






The Bag Abstract Data Type –

There are several variations  of Bag ADT 


Simple bag

Grab bag

Counting bag


There are several variations of the Bag ADT with the one described here being a simple 

bag. 

A grab bag is similar to the simple bag but the items are removed from the bag at random.

 Another common variation is the counting bag, which includes an operation that returns the number of occurrences in the bag of a given item. 


Define Bag ADT

A bag is a container that stores a collection in which duplicate values are allowed. The items, each of which is individually stored, have no particular order but they must be comparable. 

Operation -

 Bag()  : Creates a bag that is initially empty.

length(): Returns the number of items stored in the bag. Accessed using the len() function.


contains(item): Determines if the given target item is stored in the bag and returns the appropriate boolean value. Accessed using the in operator.

add(item): Adds the given item to the bag.

remove(item): Removes and returns an occurrence of item from the bag. An exception is raised if the element is not in the bag.

iterator(): Creates and returns an iterator that can be used to iterate over the collection of items.

Program


class Bag:

    def __init__(self):

self.theItems=[]

    def add( self, item ): 

self.theItems.append( item )

        #print(item)

        print(self.theItems)

    def check(self):

        value = int( input("Guess a value contained in the bag.") )

        if value in self.theItems:  

print( "The bag contains the value", value ) 

else :

print( "The bag does not contain the value", value )



myBag = Bag() 

myBag.add(19)

myBag.add(2)

myBag.add( 23 ) 

myBag.add( 19 )

myBag.add( 12 )

myBag.check()


Output-


[19]

[19, 2]

[19, 2, 23]

[19, 2, 23, 19]

[19, 2, 23, 19, 12]

Guess a value contained in the bag.2

The bag contains the value 2



Post a Comment

Post a Comment (0)

Previous Post Next Post