Пример #1
0
def main():

    # greeting
    print("Welcome to Alice's Restaurant")
    print("Open everyday except Thanksgiving.")

    # display command list
    print('Enter "a" to add a guest to the waiting list.')
    print(
        'Enter "s" to remove the next guest from the waiting list once they have been seated.'
    )
    print('Enter "q" to quit.')

    # initialize reservation list & guest tracking number
    reservationList = BinHeap()
    guestnumber = 0

    # get user imput
    command = input("Command: ")
    while command.lower() != "q":

        # add guest
        if command.lower() == "a":
            name = input("Guest name: ")
            priority = input("Guest priority: ")
            guestnumber += 1
            newguest = Guest(name, priority, guestnumber)
            reservationList.insert(newguest)
            print("A reservation for", newguest.name, "has been made.")
            print("They have been assigned a priority of",
                  newguest.priority + ".")
            print("They are currently", reservationList._heap.index(newguest),
                  "in line for a table.")
            command = input("Command: ")

        # get next guest from list
        elif command.lower() == "s":
            serving = reservationList.pop()

            # check if there are guests on list
            if serving:
                print("Now serving", serving.name)
                command = input("Command: ")

            # warn if no guests on list
            else:
                print("There are no customers on the waiting list")
                command = input("Command: ")

        # control for invalid commands
        elif command.lower() != "a" or "s":
            print("Unrecognised command! Please try again.")
            command = input("Command: ")

    # exit program
    else:
        print("Goodbye!")
        exit()
class PriorityQueue():
    """优先级队列"""
    def __init__(self, maxNode):
        self.priorityQueue = BinHeap(maxNode)
        self.dataDict = dict()

    def enqueue(self, priority, data):
        """入队"""
        self.priorityQueue.insert(priority)
        self.dataDict[priority] = data

    def dequeue(self):
        """出队"""
        pri = self.priorityQueue.delMin()
        return self.dataDict[pri]
Пример #3
0
class PriorityQueue:
    def __init__(self):
        self._heap = BinHeap()

    def isEmpty(self):
        return self._heap.isEmpty()

    def enqueue(self, item):
        self._heap.insert(item)

    def dequeue(self):
        return self._heap.delMin()

    def size(self):
        return self._heap.size()

    def __str__(self):
        return str(self._heap)
Пример #4
0
def find_split(segments):
    """Finds an appropriate pair of segments that differ enough in timbre but
    also don't lie two near the beginning or the end."""

    #initiate minimum binary heap instance
    deltas = BinHeap()

    #compares delta for each pair of segments (1,2), (2,3), etc... and save the values in deltas
    for i in range(len(segments)-2):
        deltas.insert((find_delta_segment(segments[i], segments[i+1]), i))

    #take the largest difference
    a = deltas.delMin()
    #makes sure that a is not too near the beginning (before 1/6 of song) or
    #the end (after 5/6 of song)
    while a[1] < len(segments)//4 or a[1] > (3*len(segments))//4:
        a = deltas.delMin()

    return a
Пример #5
0
def dijkstra(vertice_list,src,num_ver):
  import CPUtimer

  timer = CPUtimer.CPUTimer()
  timer.reset()
  cond = False
  parent = []
  #marca todos os vertices como nao visitados
  for i in range(num_ver):
    parent.append(-1)
  #vertice inicial tem distancia 0.  Na 1 iteracao todos os demais estao setados com 'infinidade'
  vertice_list[src].dist=0

  from binheap import BinHeap
  f = BinHeap()
  f.insert(vertice_list[src].dist,src)
  #print("Nodes:",f.total_nodes)
  #pelo numero de vertices, escolha o vertice de menor distancia atualmente no grafo.
  #Na primeira iteracao sera o source. 
  i = 0
  while(f.currentSize!=0):
  #while(i<10):
    i+=1
    
    v_min_node = f.delMin() # 1.1
    #print('key:',v_min_node.key)
    #print("Nodes:",f.total_nodes)
    v_min = vertice_list[v_min_node[1]] 

    if(v_min==None):
      continue
    v_min.visited=1#marque vertice minimo como ja visitado. Desse modo o 1.2 sera feito, pois nao sera mais contado
    #para cada vertice adjacente ao vertice minimo
    for key in v_min.adjs:# 1.3
      adj_ver = vertice_list[v_min.adjs[key].id]#pega o vertice adjacente 
      #Se a distancia atual do vertice minimo, mais o seu peso, for menor que a distancia do vert adjacente
      if(adj_ver.visited==0 and  v_min.dist + v_min.weights[key] < adj_ver.dist ):
        adj_ver.dist = v_min.dist + v_min.weights[key] #a distancia do vertice adjacente tera esse novo valor
        parent[adj_ver.id] = v_min.id # a pos que era do vertice adjacente, sera do menor v agora
        f.insert(adj_ver.dist,adj_ver.id)