Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python เพื่อใช้งาน Stack โดยใช้ One Queue


เมื่อจำเป็นต้องใช้สแต็กโดยใช้คิวเดียว คลาส 'Stack_structure' จำเป็นพร้อมกับคลาส Queue_structure มีการกำหนดเมธอดที่เกี่ยวข้องในคลาสเหล่านี้เพื่อเพิ่มและลบค่าจากสแต็กและคิวตามลำดับ

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

ตัวอย่าง

class Stack_structure:
   def __init__(self):
      self.q = Queue_structure()

   def check_empty(self):
      return self.q.check_empty()

   def push_val(self, data):
      self.q.enqueue_operation(data)

   def pop_val(self):
      for _ in range(self.q.size_calculate() - 1):
         dequeued = self.q.dequeue_operation()
         self.q.enqueue_operation(dequeued)
      return self.q.dequeue_operation()

class Queue_structure:
   def __init__(self):
      self.items = []
      self.size = 0

   def check_empty(self):
      return self.items == []

   def enqueue_operation(self, data):
      self.size += 1
      self.items.append(data)

   def dequeue_operation(self):
      self.size -= 1
      return self.items.pop(0)

   def size_calculate(self):
      return self.size

my_instance = Stack_structure()

print('Menu')
print('push <value>')
print('pop')
print('quit')

while True:
   my_input = input('What operation would you like to perform ? ').split()

   operation = my_input[0].strip().lower()
   if operation == 'push':
      my_instance.push_val(int(my_input[1]))
   elif operation == 'pop':
      if my_instance.check_empty():
         print('The stack is empty.')
      else:
         print('The deleted value is : ', my_instance.pop_val())
   elif operation == 'quit':
      break

ผลลัพธ์

Menu
push <value>
pop
quit
What operation would you like to perform ? push 89
What operation would you like to perform ? push 43
What operation would you like to perform ? push 76
What operation would you like to perform ? push 56
What operation would you like to perform ? pop
The deleted value is : 56
What operation would you like to perform ? quit

คำอธิบาย

  • คลาส 'Stack_structure' ถูกสร้างขึ้นเพื่อเริ่มต้นรายการว่าง

  • วิธีการ 'check_empty' ถูกกำหนดเพื่อดูว่าสแต็กว่างเปล่าหรือไม่

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'push_val' ซึ่งเพิ่มองค์ประกอบลงในสแต็ก

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'pop_val' เพื่อลบองค์ประกอบออกจากสแต็ก

  • คลาส 'Queue_structure' ถูกสร้างขึ้นเพื่อเริ่มต้นรายการว่างและกำหนดขนาดของรายการเป็น 0

  • วิธีการ 'check_empty' ถูกกำหนดเพื่อดูว่าคิวว่างหรือไม่

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'enqueue_operation' ซึ่งเพิ่มองค์ประกอบลงในคิว

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'dequeue_operation' ซึ่งจะลบองค์ประกอบออกจากคิว

  • มีการกำหนดวิธีการอื่นที่ชื่อว่า 'size_calculate' ซึ่งกำหนดขนาดของคิว

  • อินสแตนซ์ของ 'Stack_structure' นี้ถูกกำหนดไว้แล้ว

  • มีสี่ตัวเลือกให้เลือก ได้แก่ เมนู กด ป๊อป และออก

  • ขึ้นอยู่กับอินพุตที่กำหนดโดยผู้ใช้ การดำเนินการจะดำเนินการกับองค์ประกอบของสแต็ก

  • เอาต์พุตจะแสดงบนคอนโซล