def createArrivalQueue(fname):
    q = Queue()
    infile = open(fname)
    for line in infile:
        time, items = line.split()
        q.enqueue(Customer(time,items))
    infile.close()
    return q
 def __init__(self, arrivalQueue, avgTime):
     self.time = 0                # ticks so far in simulation
     self.arrivals = arrivalQueue # queue of arrival events to process
     self.line = Queue()          # customers waiting in line
     self.serviceTime = 0         # time left for current customer
     self.totalWait = 0           # sum of wait time for all customers
     self.maxWait = 0             # longest wait of any customer
     self.customerCount = 0       # number of customers processed
     self.maxLength = 0           # maximum line length
     self.ticksPerItem = avgTime  # time to process an item
Exemplo n.º 3
0
 def __inti__(self):
     """possibly useful instance variables"""
     self.myCurrent_Card = 0        # my currently displayed card
     self.otherCurrent_Card = 0        # other currently displayed card
     self.currentState_TurnTracker = 0        # keeps track of the state of play
     self.dealingPile = Stack()
     self.myPayingPile = Stack()
     self.myStoragePile = Stack()
     self.otherPlayingPile = Stack()
     self.otherStoragePile = Stack()
     self.lootPile = Queue()
     self.otherlootpile = Queue()
    def __init__(self, size, services=[], workloads=[]):
        _size = int(size)
        _services = services
        _workloads = workloads
        if _size < 1:
            raise Exception("Illegal size for QueueNetwork")
        for i in range(len(_services)):
            _services[i] = int(_services[i])
            if _services[i] < 1:
                raise Exception("Illegal service rates for QueueNetwork")
        for i in range(len(_workloads)):
            _workloads[i] = int(_workloads[i])
            if _workloads[i] < 0:
                raise Exception("Illegal workloads for QueueNetwork")
        if not _services:
            _services = [1 for i in range(_size)]
        if not _workloads:
            _workloads = [0 for i in range(_size)]

        # Member fields init.
        self.queues = [
            Queue(_services[i], _workloads[i]) for i in range(_size)
        ]
        self.totalWorkload = np.sum(_workloads)
        self.size = _size
        self.time = 0
Exemplo n.º 5
0
def cinema_queue(queue, till_show, tsold_time):
	viewers=Queue()                         #количество зрителей
	sold_ticket=[]                          #количество купленных билетов

	for i in range (10):
		viewers.enqueue("Зритель "+str(i))      #зритель приобрёл билет

	now=time.time()                         #с 1 января 1970 года прошло секунд
	a=now                                   #зафиксировать момент времени
	c=0                                     #переменная для записи количества прошедшего времени
	t=0                                     #время до конца фильма
	x=0                                     #переменная для проверки возможности приобретения билетов до начала киносеанса
	while x>=0 and not viewers.is_empty():  #если фильм ещё не начался и в очереди есть зрители
		now=time.time()                 #прошедшее время с начала отсчета в секундах
		b=now                           #зафиксировать момент времени
		c=b-a                           #от момента a до b прошло c секунд
		t=till_show-c                   #время, остающееся до начала фильма
		print("До начала фильма осталось ", t, "секунд")
		#print("С начала отсчёта прошло ", c, " секунд")
		r=random.randint(10,15)         #рандомное время ожидания в очереди (от 20 до 30 секунд)
		x=t-r                           
		if x>0:
				print("Предположительное время ожидания: ", r, " секунд")
				time.sleep(r)                   #временная задержка
				person=viewers.dequeue()        #последнее значение, добавленное в очередь Зрители
				print("Зритель ", person)
				sold_ticket.append(person)      #количество зрителей на киносеансе
		else:
				print("Киносеанс уже начался. Продажа билетов завершена.")
	print("Количество приобретенных на киносеанс билетов: ", len(sold_ticket))
	return sold_ticket
Exemplo n.º 6
0
    def __init__(self):
        """Creating the different piles needed for the game, and initializing
        all instance variables"""

        self.playingPile = Stack()
        self.cpu_playingPile = Stack()
        self.storagePile = Queue()
        self.cpu_storagePile = Queue()
        self.lootPile = Queue()
        self.dealingPile = Stack()
        self.deck = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # the numbers on the deck cards are initialized
        self.current_playerCard = None              # This card will hold the value of the current card in game for the human player
        self.current_cpuCard = None                 # This card will hold the value of the current card in game for the computer player
class Stack:
    def __init__(self, length=5):
        self.q1 = Queue(length)
        self.q2 = Queue(length)

    # O(1)
    def push(self, x):
        self.q1.enqueue(x)

    # O£¨n£©
    def pop(self):
        if self.q1.isEmpty():
            raise Exception("Empty Stack")
        while len(self.q1) > 1:
            self.q2.enqueue(self.q1.dequeue())
        v = self.q1.dequeue()
        self.q1, self.q2 = self.q2, self.q1
        return v

    # O(1)
    def isEmpty(self):
        return self.q1.isEmpty()
Exemplo n.º 8
0
Arquivo: BFS.py Projeto: JC5137/CLRS
 def BFS(self, Graph, start):
     self.__setAttribute(Graph)
     self.color[start] = 0
     self.distance[start] = 0
     self.prev[start] = None
     Q = Queue(len(Graph.vertexs))
     Q.EnQueue(start)
     while not Q.IsEmpty():
         u = Q.DeQueue()
         for v in Graph.edges[u]:
             if self.color[v] == -1:
                 self.color[v] = 0
                 self.distance[v] = self.distance[u] + 1
                 self.prev[v] = u
                 Q.EnQueue(v)
         self.color[u] = 1
Exemplo n.º 9
0
class WarCardGame:

    """The different properties of the War card game"""

    def __init__(self):
        """Creating the different piles needed for the game, and initializing
        all instance variables"""

        self.playingPile = Stack()
        self.cpu_playingPile = Stack()
        self.storagePile = Queue()
        self.cpu_storagePile = Queue()
        self.lootPile = Queue()
        self.dealingPile = Stack()
        self.deck = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # the numbers on the deck cards are initialized
        self.current_playerCard = None              # This card will hold the value of the current card in game for the human player
        self.current_cpuCard = None                 # This card will hold the value of the current card in game for the computer player

    def prepare_dealPile(self):
        """Prepares the dealing deck before the game starts."""
        deck_cards = self.deck * 5
        for num in deck_cards:                              # This goes to every card in the deck
                self.dealingPile.push(num)                  # This appends the card number to the dealing pile 5 times.
                                                            # After iterating through the deck cards, the dealing pile will have 50 cards, with values from 0 to 9 repeated 5 times each.
        self.shuffle_dealingPile()                          # The dealing pile is shuffled after getting the 50 cards.

    def shuffle_dealingPile(self):
        """ This randomly shuffles the dealing pile."""
        random.shuffle(self.dealingPile.items)

    def deal(self):
        """This Deals 25 cards to each playing pile, always taking the one at the top.
        It will deal one card to player one, then one to computer, and it will
        repeat the process until both players have 25 cards and the dealing pile
        is empty."""
        self.prepare_dealPile()                                      # Calls the funtion that prepares the dealing pile by putting the cards in and shuffling it.
        first_popped_card = 0
        second_popped_card = 0
        while self.dealingPile.size() > 0:                          # Cards will be dealt as long as there are cards in the dealing pile
            first_popped_card = self.dealingPile.pop()
            self.playingPile.push(first_popped_card)                # The card dealt is placed on top of the pile
            second_popped_card = self.dealingPile.pop()
            self.cpu_playingPile.push(second_popped_card)           # The card dealt is placed on top of the pile

    def refilling_playingPile(self):
        """Refills the playing pile with the storage pile cards"""

        if self.storagePile.size() > 0:
            for card in self.storagePile.q:
                self.playingPile.push(self.storagePile.dequeue())
        else:
            self.endGame('Computer Player')                         # This Ends the game

    def refilling_cpuPile(self):
        """This Refills the cpu playing pile."""

        if self.cpu_storagePile.size() > 0:
            for card in self.cpu_storagePile.q:
                self.cpu_playingPile.push(self.cpu_storagePile.dequeue())
        else:
            self.endGame('Human Player')                            # This ends the game

    def draw_card(self):
        """Draws one card from each playing pile so that they can be
        compared."""
        if self.playingPile.size() > 0:                             # when bigger than zero
            self.current_playerCard = self.playingPile.pop()
        else:
            self.refilling_playingPile()
        if self.cpu_playingPile.size() > 0:                         # when bigger than zero
            self.current_cpuCard = self.cpu_playingPile.pop()
        else:
            self.refilling_cpuPile()

    def compare_cards(self):
        """Compares the rank of the cards drawn to decide the
        following step in the game."""
        if self.current_playerCard > self.current_cpuCard:          # This is when the values of cards of the player are bigger than the values of the cards of the computer
            self.storagePile.enqueue(self.current_playerCard)
            self.storagePile.enqueue(self.current_cpuCard)
            self.current_playerCard = None                          # This instatiates these variables to None after they have been used.
            self.current_cpuCard = None
        elif self.current_cpuCard > self.current_playerCard:        # This is when the computer has better cards than player
            self.cpu_storagePile.enqueue(self.current_cpuCard)
            self.cpu_storagePile.enqueue(self.current_playerCard)
            self.current_cpuCard = None
            self.current_playerCard = None
        else:                                                                       # This section deals with the war part of the game, when both cards are of the same rank
            self.move_my_loot(self.current_playerCard, self.current_cpuCard)     # First, the two cards are placed in the loot pile
            self.default_current_cards()                                            # This sets the current card variables to the default
            self.war_event()

    def move_my_loot(self, playerCard, cpuCard):                                 # This places the cards into a loot pile.
        """Puts the two cards onto the loot pile, one after the other."""
        self.lootPile.enqueue(playerCard)
        self.lootPile.enqueue(cpuCard)

    def default_current_cards(self):                                                # if values of cards equal None
        """Sets the value of the variables for current cards to default None."""
        self.current_playerCard = None
        self.current_cpuCard = None

    def endGame(self, winner):
        """Checks if the player has enough cards to keep playing"""
        print ("We have a winner!")                             # announces that there is a winner
        print ("The " + winner + " won")
        next_step = raw_input("Do you want to try again? Type Y for yes or N for no.")
        while next_step == "N" or next_step == "n" or next_step == "Y" or next_step == "y":
            if next_step == "N" or next_step == "n":            # if player inputs "no" the game ends
                print ("Thank you for playing the game.")
                sys.exit()                                      # this exits the game
            else:
                print('Start Again:')                           # allows the game to start over.
                self.Play_game()
        else:
            while next_step != "N" or next_step != "n" or next_step != "Y" or next_step != "y":
                print ("That was not a valid input. Try again.")    # keeps prompting the player until he puts in a valid input
                next_step = raw_input("Do you want to try again? Type Y for yes or N for no.")

    def war_event(self):
        """Controls what happens when the two players draw the same card."""
        self.draw_card()
        self.move_my_loot(self.current_playerCard,self.current_cpuCard)
        self.draw_card()                                        # Each player draws a new card from the top of their playing piles
        print('player Card: ' + str(self.current_playerCard))
        print('cpu Card: ' + str(self.current_cpuCard))

        if self.current_playerCard > self.current_cpuCard:
            self.storagePile.enqueue(self.current_playerCard)
            self.storagePile.enqueue(self.current_cpuCard)
            self.storagePile.enqueue(self.lootPile.dequeue())
            self.default_current_cards()
        elif self.current_cpuCard > self.current_playerCard:
            self.cpu_storagePile.enqueue(self.current_cpuCard)
            self.cpu_storagePile.enqueue(self.current_playerCard)
            self.cpu_storagePile.enqueue(self.lootPile.dequeue())
            self.default_current_cards()
        else:
            self.move_my_loot(self.current_playerCard, self.current_cpuCard)
            self.war_event()

    def Play_game(self):                        # this function allows the game to be played
        """This Plays the game"""
        self.__init__()
        self.deal()
        while True:
            self.draw_card()
            print('player Card: ' + str(self.current_playerCard))
            print('cpu Card: ' + str(self.current_cpuCard))
            self.compare_cards()
 def __init__(self, length=5):
     self.q1 = Queue(length)
     self.q2 = Queue(length)
Exemplo n.º 11
0
def isPalindrome(phrase):
    forward = Queue()
    reverse = Stack()
    extractLetters(phrase, forward, reverse)
    return sameSequence(forward, reverse)
Exemplo n.º 12
0
s.pop()
s.pop()
s.push(21)
print(s)

s2 = Stack(17)
s2.push(21)
print(s == s2)

s.push(12)
print(s, s.top())

print(s.search(44), s.search(21))

q = Queue(44)
q.enqueue(39)
q.enqueue(31)
q.enqueue(42)

print(q)
print(q.size(), q.back(), q.front())
q.dequeue()

q2 = Queue()
q2.enqueue(56)

print(q != q2)

q2.enqueue(67)
q2.print_queue()
Exemplo n.º 13
0
		viewers.enqueue("Зритель "+str(i))      #зритель приобрёл билет

	now=time.time()                         #с 1 января 1970 года прошло секунд
	a=now                                   #зафиксировать момент времени
	c=0                                     #переменная для записи количества прошедшего времени
	t=0                                     #время до конца фильма
	x=0                                     #переменная для проверки возможности приобретения билетов до начала киносеанса
	while x>=0 and not viewers.is_empty():  #если фильм ещё не начался и в очереди есть зрители
		now=time.time()                 #прошедшее время с начала отсчета в секундах
		b=now                           #зафиксировать момент времени
		c=b-a                           #от момента a до b прошло c секунд
		t=till_show-c                   #время, остающееся до начала фильма
		print("До начала фильма осталось ", t, "секунд")
		#print("С начала отсчёта прошло ", c, " секунд")
		r=random.randint(10,15)         #рандомное время ожидания в очереди (от 20 до 30 секунд)
		x=t-r                           
		if x>0:
				print("Предположительное время ожидания: ", r, " секунд")
				time.sleep(r)                   #временная задержка
				person=viewers.dequeue()        #последнее значение, добавленное в очередь Зрители
				print("Зритель ", person)
				sold_ticket.append(person)      #количество зрителей на киносеансе
		else:
				print("Киносеанс уже начался. Продажа билетов завершена.")
	print("Количество приобретенных на киносеанс билетов: ", len(sold_ticket))
	return sold_ticket

q1=Queue()
sold=cinema_queue(q1, 40, 10)
print(sold)
Exemplo n.º 14
0
class War:
    def __inti__(self):
        """possibly useful instance variables"""
        self.myCurrent_Card = 0        # my currently displayed card
        self.otherCurrent_Card = 0        # other currently displayed card
        self.currentState_TurnTracker = 0        # keeps track of the state of play
        self.dealingPile = Stack()
        self.myPayingPile = Stack()
        self.myStoragePile = Stack()
        self.otherPlayingPile = Stack()
        self.otherStoragePile = Stack()
        self.lootPile = Queue()
        self.otherlootpile = Queue()
    def add_dealingPile(self):
        """adds the shuffled decks of cards to the dealer's pile"""
        card = 0
        i = 0
        while i != 4:
            while card != 10:
                card = 0
                self.dealingPile.push(card)
                card +=1
            i + 1

    def deal(self):
        """deals out 25 cards from to each player's playing pile from shuffled dealers pile"""
        self.add_dealingPile()
        Dealing_Deck = self.dealingPile()
        while Dealing_Deck.size() != 25:
            self.myPayingPile.push(Dealing_Deck.top())
            self.Dealing_Deck.pop()
        while Dealing_Deck.size() != 0:
            self.otherPlayingPile.push(Dealing_Deck.top())
            self.Dealing_Deck.pop()

    def make_move(self):
        """initiates a round of play and communicates play-by-play during the round
    returns true when the game is still in play
    returns false when the game is over
    Communicates an appropriate message about whether the user beat the computer"""
        round = 0
        self.deal()
        self.move_my_loot()
        self.move_other_loot()
        self.move_my_storage()
        self.move_other_storage()
        while self.myPayingPile.size() != None and self.myStoragePile.size() != None and self.lootPile.size() != None:
            round += 1
            self.myCurrent_Card = self.myPayingPile.top()
            self.otherCurrent_Card = self.otherPlayingPile.top()


    def remove_my_card(self):
        """Precondition: myPlayingPile is not empty
    If it is not empty, the function removes a card from myPlayingPile,
    returning the stored value"""
        if self.myPayingPile.size() != None:
            self.myPayingPile.pop()

    def remove_other_card(self):
        """Precondition: otherPlayingPile is not empty
    If it is not empty, the function removes a card from otherPlayingPile,
    returning the stored value"""
        if self.otherPlayingPile.size() != None:
            self.otherPlayingPile.pop()

    def display_card(self):
        """displays a card on the screen and returns the value"""
        display = []
        usercard=self.myCurrent_Card.top()
        display.append(usercard)
        computercard=self.otherCurrent_Card.top()
        display.append(computercard)
        print display
        return display

    def I_declair_War(self):
        """If two cards are the same ir does this step to find to wins and if not does it again until someone wins"""
        myC_one = self.myCurrent_Card()
        self.remove_my_card()
        self.myCurrent_Card = self.myPayingPile.top()
        myC_Two = self.myCurrent_Card()
        self.remove_my_card()
        self.myCurrent_Card = self.myPayingPile.top()
        myC_Three= self.myCurrent_Card()
        self.remove_my_card()
        self.myCurrent_Card = self.myPayingPile.top()
        myC_Four = self.myCurrent_Card()
        self.remove_my_card()
        #----------------------------
        otherC_one = self.remove_my_card()
        self.remove_other_card()
        self.otherCurrent_Card = self.otherPlayingPile.top()
        otherC_Two = self.remove_my_card()
        self.remove_other_card()
        self.otherCurrent_Card = self.otherPlayingPile.top()
        otherC_Three = self.remove_my_card()
        self.remove_other_card()
        self.otherCurrent_Card = self.otherPlayingPile.top()
        otherC_Four = self.remove_my_card()
        self.remove_other_card()

        Mytotal = myC_one + myC_Two + myC_Three + myC_Four
        othertotal = otherC_one + otherC_Two + otherC_three + otherC_Four

        if Mytotal == othertotal:
            print "War!"
            self.I_declair_War()
        elif Mytotal > othertotal:
            print "Human Win!"
        else:
            print "Computer Win!"
    def compare_cards(self):
        """compares myCurrent to otherCurrent and behaves appropriately"""
        if self.myCurrent_Card() == self.otherCurrent_Card():
            print "War"
            self.I_declair_War()
        elif self.myCurrent_Card() < self.otherCurrent_Card():
            print "Computer Win!"
            self.otherlootpile.enqueue(self.myCurrent_Card)
        else:
            print "Human Win!"
            self.lootPile.enqueue(self.otherCurrent_Card)
    def move_my_loot(self):
        """moves everything from lootPile to myStoragePile"""
        while self.lootPile.size() == None:
            self.myStoragePile.push(self.lootPile.dequeue())

    def move_other_loot(self):
        """moves everything from lootPile to otherStoragePile"""
        while self.otherlootpile.size() == None:
            self.otherStoragePile.push(self.otherlootpile.dequeue())
    def move_my_storage(self):
        """moves everything from myStoragePile to myPlayingPile"""
        while self.myStoragePile.size() == None:
            self.myPayingPile.push(self.myStoragePile.top())
            self.myPayingPile.pop()

    def move_other_storage(self):
        """moves everything from otherStoragePile to otherPlayingPile"""
        while self.otherStoragePile.size() == None:
            self.otherPlayingPile.push(self.otherStoragePile.top())
            self.otherStoragePile.pop()
class CheckerSim(object):

    #------------------------------------------------------------

    def __init__(self, arrivalQueue, avgTime):
        self.time = 0                # ticks so far in simulation
        self.arrivals = arrivalQueue # queue of arrival events to process
        self.line = Queue()          # customers waiting in line
        self.serviceTime = 0         # time left for current customer
        self.totalWait = 0           # sum of wait time for all customers
        self.maxWait = 0             # longest wait of any customer
        self.customerCount = 0       # number of customers processed
        self.maxLength = 0           # maximum line length
        self.ticksPerItem = avgTime  # time to process an item

    #------------------------------------------------------------

    def run(self):
        while (self.arrivals.size() > 0 or
               self.line.size() > 0 or
               self.serviceTime > 0):
            self.clockTick()

    #------------------------------------------------------------

    def averageWait(self):
        return float(self.totalWait) / self.customerCount

    #------------------------------------------------------------

    def  maximumWait(self):
        return self.maxWait

    #------------------------------------------------------------

    def maximumLineLength(self):
        return self.maxLength            

    #------------------------------------------------------------

    def clockTick(self):
        # one tick of time elapses
        self.time += 1
        
        # customer(s) arriving at current time enter the line
        while (self.arrivals.size() > 0 and
               self.arrivals.front().arrivalTime == self.time):
            self.line.enqueue(self.arrivals.dequeue())
            self.customerCount += 1
        # if line has reached a new maximum, remember that
        self.maxLength = max(self.maxLength, self.line.size())

        # process items
        if self.serviceTime > 0:
            # a customer is currently being helped 
            self.serviceTime -= 1
        elif self.line.size() > 0:
            # help the next customer in line
            customer = self.line.dequeue()
            #print self.time, customer      # nice tracing point
            # compute and update statistics on this customer
            self.serviceTime = customer.itemCount * self.ticksPerItem
            waitTime = self.time - customer.arrivalTime
            self.totalWait += waitTime
            self.maxWait = max(self.maxWait, waitTime)