コード例 #1
0
class SendSMS:
    def __init__(self, bulk_sms_provider):
        self.bulk_sms_provider = bulk_sms_provider
        self.msg_queue = Queue()

    def sms_queue(self, data):
        self.msg_queue.enqueue({'data': data})

    def send(self):
        while not self.msg_queue.isEmpty():
            msg = self.msg_queue.dequeue()
            bulk_sms_provider = self.bulk_sms_provider

            url = bulk_sms_provider.api_endpoint
            headers = literal_eval(
                bulk_sms_provider.headers)  #convert str to dict datatype
            data = msg['data']

            if bulk_sms_provider.username and bulk_sms_provider.password:
                response = requests.post(url=url,
                                         headers=headers,
                                         data=data,
                                         auth=(bulk_sms_provider.username,
                                               bulk_sms_provider.password))
            else:
                response = requests.post(url=url, headers=headers, data=data)

            return response
コード例 #2
0
def radix_sorting_machine(num_list: list) -> list:
    # main_bin 设定
    main_bin = Queue()
    main_bin.items = num_list
    # 10个digit bin
    bin_dic = [None] * 10
    # 最大数字位计算
    max_digit = 0
    for i in num_list:
        current_len = len(str(i))
        if current_len > max_digit:
            max_digit = current_len
    # 逐位排序,便览各位
    for n in range(1, max_digit + 1):
        while not main_bin.isEmpty():  # 便览main_bin中的数
            current_num = main_bin.dequeue()
            current_num_copy = current_num
            # 计算倒数第n位的数字
            m = 1
            while m <= n:
                remainder = current_num_copy % 10
                current_num_copy = current_num_copy // 10
                m += 1
            # 存储进remainder号bin
            if bin_dic[remainder] == None:
                bin_dic[remainder]: Queue = Queue()
            bin_dic[remainder].enqueue(current_num)
            # 逐个digit bin弹出数字到main_bin
        for digit_bin in bin_dic:
            while digit_bin != None and not digit_bin.isEmpty():
                main_bin.enqueue(digit_bin.dequeue())

    return main_bin.items
コード例 #3
0
def bfs(g, start):
    visited = []
    q = Queue()
    q.enqueue(start)
    visited.append(start)

    while not q.isEmpty():
        v = q.dequeue()
        for n in g.getVertex(v).getConnections():
            if n.id not in visited:
                q.enqueue(n.id)
                visited.append(n.id)

    return visited
コード例 #4
0
def simulation(numSeconds, pagesPerMinute):

    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask():
            #print("cursecond is %d"%currentSecond)
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and \
            (not printQueue.isEmpty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append( \
                nexttask.waitTime(currentSecond))
            labprinter.startNext(nexttask)
        labprinter.tick()
    averageWait = sum(waitingtimes) / len(waitingtimes)
    print("Avg wait %6.2f secs %3d tasks remaining." %
          (averageWait, printQueue.size()))
コード例 #5
0
class Balcao:
    """
    Descreve um balcão e a respectiva fila de passageiros
    """
    def __init__(self, n_balcao, num_bag):
        """
        Inicializa um balcão com o número indicado
        :param n_balcao: número do balcão
        :param num_bag: o número máximo de bagagens permitido por passageiro
        """

        self.n_balcao = n_balcao

        self.fila = Queue()
        self.inic_atend = 0
        self.passt_atend = 0
        self.numt_bag = 0
        self.tempt_esp = 0
        self.bag_utemp = randint(1, num_bag)

    def obtem_n_balcao(self):
        """
        Devolve o valor de n_balcao
        :return: n_balcao
        """

        return self.n_balcao

    def obtem_fila(self):
        """
        Devolve o valor da fila
        :return: fila
        """

        return self.fila

    def muda_inic_atend(self, tempo_atendimento):
        """
        Acumula em inic_atend o “valor” do tempo de atendimento do passageiro
        :param tempo_atendimento: tempo de atendimento
        :return: None
        """

        self.inic_atend = tempo_atendimento

    def incr_passt_atend(self):
        """
        Incrementa em 1 o passt_atend - total de passageiros atendidos por este balcão
        :return: None
        """

        self.passt_atend += 1

    def muda_numt_bag(self, passageiro):
        """
        Acumula em numt_bag do balcão, o bag_pass do passageiro quando este termina de ser atendido
        :param passageiro: passageiro processado
        :return: None
        """

        self.numt_bag += passageiro.obtem_bag_pass()

    def muda_tempt_esp(self, tempo_espera):
        """
        Acumula em tempt_esp o “t” tempo de espera do passageiro
        :param tempo_espera: Tempo de espera
        :return: None
        """

        self.tempt_esp += tempo_espera

    def __str__(self):
        """
        Retorna o balcão como uma string legível para o utilizador
        Output esperado:
            Quando tem passageiros na fila:
                Balcão 2 tempo 2 : - [b:4 t:1] [b:2 t:2] -
            Quando não tem passageiros na fila:
                Balcão 0 tempo 1 : -
        :return: string
        """

        # Formata a lista de passageiros consoante as especificações
        if self.fila.isEmpty():
            str_pass = "******"
        else:
            passageiros_como_str = [
                str(passageiro) for passageiro in self.fila.items
            ]
            str_pass = "******".format(" ".join(passageiros_como_str))

        return "Balcão {} tempo {} : {}".format(self.obtem_n_balcao(),
                                                self.tempt_esp, str_pass)
コード例 #6
0
            return False  # 洗完需要换车
        else:
            return True


washer = Washer()
car_queue = Queue()  # 洗车排队,只有10个车位
current: Car = None  # 空档状态
wait_time = []
# 模拟两小时
randomor = random.Random()
for second in range(7200):
    if randomor.randrange(
            600) == 0 and car_queue.size() < 20:  # 概率上600秒来一辆车,概率运算一定会一直进行
        new_car = Car()
        new_car.timestamp = second  # 标记开始等待时间
        car_queue.enqueue(new_car)  # 排到队尾

    # 洗车
    # if washer.current_car_time == 0 and not car_queue.isEmpty():  # 无车在洗,队列有车
    #     current = car_queue.dequeue()  # 队尾为下一个车
    if not washer.wash(current):  # 无车在洗
        if not car_queue.isEmpty():  # 有车可换
            current = car_queue.dequeue()
            wait_time.append(second - current.timestamp)  # 存储车辆等待时间
        else:  # 无车可换
            current = None

print('总共洗车:', len(wait_time), '辆,平均等待时间:',
      sum(wait_time) / len(wait_time), ",还剩", car_queue.size(), '辆车没洗')
コード例 #7
0
c = Tree("c")
d = Tree("d")
e = Tree("e")
f = Tree("f")
g = Tree("g")
h = Tree("h")
i = Tree("i")
j = Tree("j")

a.add_left(b)
a.add_right(c)
b.add_left(d)
b.add_right(e)
d.add_right(g)
g.add_left(h)
e.add_left(f)
c.add_left(i)
c.add_right(j)

from pythonds import Queue

q = Queue()
q.enqueue(a)

while not q.isEmpty():
    cur = q.dequeue()
    print(cur.data)
    if cur.left:
        q.enqueue(cur.left)
    if cur.right:
        q.enqueue(cur.right)