Pages

Search This Blog

November 26, 2012

coffee-can problem

# coffee-can problem from "Science of Programming" by David Gries
class Bean(object):
    """
    bean class
    - has colorattribute. valid colors - BLACK or WHITE
    """
    def __init__(self, color):
        assert color == "WHITE" or color =="BLACK"
        self.color = color
    def __str__(self):
        return self.color
class Container(object):
   """
    container for beans
    """
    def __init__(self, l):
        self.beans = {}
        self.length =l
        self.currentIndex = 0
    def initialize(self):
        import random
        for x inxrange(self.length):
            t = random.randint(0, self.length)
            if t % 2 == 0: # even - create black bean
               b= Bean("BLACK")
                self.beans[self.currentIndex] = b
            else: # create white bean
                b =Bean("WHITE")
                self.beans[self.currentIndex] = b
            self.currentIndex = self.currentIndex + 1
    def__str__(self):
        return '\n'.join(str(k) + ': ' + str(self.beans[k])
                         for k in self.beans)
       
    def addBlackBean(self):
        b = Bean("BLACK")
        self.beans[self.currentIndex] = b
        self.currentIndex =self.currentIndex + 1
                
    def coffeeCan(self):
        """
        pull out 2 beans in random
        - ifthey are of same color, remove them and add a black bean
        - if they are of different color, throw black bean out and return
           white bean to the container
        """
        import random
        first, second = -1, -1
        while True:
           if(len(self.beans) == 1):
                print 'remaining coffee-can: ', self
                return
            
##           while True: # to make sure we pull out bean in container
##                first = random.randint(0, self.currentIndex)
##                if firstinself.beans: break
            first = random.choice(self.beans.keys())
                
            whileTrue:
                # to make sure we pull 2 different beans and
                # a bean from container
                ## second =random.randint(0, self.currentIndex)
                second = random.choice(self.beans.keys())
                if second != first and second inself.beans: break
            print 'pulling out ', first, ' and ', second
            if self.beans[first].color ==self.beans[second].color:
                print 'same color, removing them and adding a black bean'
                delself.beans[first]
                del self.beans[second]
                self.addBlackBean()
            else:
               print 'different colors. removing black bean'
                if self.beans[first].color == "BLACK":
                    delself.beans[first]
                else:
                    del self.beans[second]
            print self
c =Container(4)
c.initialize()
print c
c.coffeeCan()

No comments:

Post a Comment