将整数队列的输入作为输入,并将其转换为具有平方元素的队列



squareElems:一个函数,它将整数队列作为输入,并将其转换为包含相同平方元素的队列。例如,如果输入队列最初包含(2,4,6 8(,则应用此函数应将其内容更改为:(4,16,36,64(。

类队列:

def __init__ (self):
"""Create an empty queue."""
self._data = [ ] # nonpublic list instance
def __len__(self):
"""Return the number of elements in the queue."""
return len(self._data)
def is_empty(self):
"""Return True if the queue is empty."""
return len(self._data) == 0
def enqueue(self, e):
"""Add element e to the rear of the queue."""
self._data.insert(0, e) # new item stored at the beginning of the list
def peek(self):
"""Return (but do not remove) the element at the  front of the queue. Raise Empty exception if the queue is empty. """
if self.is_empty():
raise QueueEmpty('Queue is empty')
return self._data[-1] # the last item in the list
def dequeue(self):
"""Remove and return the element from the front of the queue (FIFO). Raise Empty exception if the queue is empty. """
if self.is_empty():
raise QueueEmpty("Queue is empty")
return self._data.pop() # remove the last item item from list

def __str__(self):
stack_rep = "Current contents of the queue:n"

for el in self._data:
stack_rep +=str(el) + ' '

return stack_rep
def sqaureElems(self):
def sqaure(n):
return n**2
number = int(input('Please enter a number: '))
number2 = square(number)
return number2


print('Current contents of the queue:')

print('Calling sqaureElems() on the queue...:')
print('Current contents of the queue')

def-main((:

st = Queue()
st.is_empty()
st.enqueue(2)
st.enqueue(4)
st.enqueue(6)
st.enqueue(8)
st.peek()
st.dequeue()


如果name==">main":main((

输出显示如下:

队列的当前内容2 4 6 8

正在对队列调用sqaureElems((。。。

队列的当前内容:4 16 32 64

如果我正确理解了您的需求,您可以这样做:

from queue import Queue

def sqaure_elems(q):
q.put("STOP")
while (item := q.get()) != "STOP":
q.put(item * item)
q.task_done()
q.task_done()
def main():
q = Queue()
for item in range(2, 10, 2):
q.put(item)
sqaure_elems(q)
while not q.empty():
print(q.get())
q.task_done()
q.join()

if __name__ == "__main__":
main()

注意:

海象运算符(:=(自Python 3.8+起可用。

最新更新