使用enqueue将数字生成器添加到堆栈数据结构

时间:2017-12-09 10:20:57

标签: python

我刚开始实施队列,需要一些帮助才能练习。

说,我正在使用enqueue排队4个人,我想在输出中添加一个函数,从1到10显示一个随机数'x',持续4次,符合以下条件:

如果'x'在1-8之间,那么名称将被添加到队列中。 如果'x'是9或10,程序将把'exit'推送到堆栈数据结构并退出循环4并用pop方法显示堆栈上的所有名称

此外,条件是显示最大名称数为4,最小值为0。 然后,将显示已在输出中添加到队列的名称的结果。

如何添加?

import random  # We will need this to generate the random number

class Queue:
    def __init__(self):
        self.container = []

    def isEmpty(self):
        return self.size() == 0  

    def enqueue(self, item):
        self.container.append(item)

    def dequeue(self):
        self.container.pop(0)

    def size(self):
        return len(self.container)

    def peek(self) :
        return self.container[0]

q = Queue()
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name
    print(q.items)

我希望实现像这样的输出

Number generated: 
8
Number generated: 
3
Number generated: 
2
Number generated: 
10

Completed.

Names of people added to queue:
#3 - James
#1 - Sam
#2 – Peter

1 个答案:

答案 0 :(得分:1)

听起来你想生成一个随机数,如果随机数满足某些条件,则将一个值排队,否则打破循环。使用您对Queue类的定义,以下内容应执行此操作:

import random  # We will need this to generate the random number

q = Queue()  # Initialize the Queue just like you had it
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name

希望这有助于解决您的问题。