Home > Article > Backend Development > What does the stack in python refer to?
A stack is an ordered collection of items, where adding and removing new items always occurs at the same end. This end is often called the "top." The end corresponding to the top is called the "bottom".
As described in the picture, stack s=(a1,a2,…an-1,an). The last one pushed onto the stack is an, and the first one popped off the stack is also an. So the stack complies with the LIFO principle.
LIFO
LIFO, that is, the last-in-first-out sorting principle. It sorts based on the length of time within the collection. Newer items are near the top and older items are near the bottom. The bottom of the stack is important because items near the bottom of the stack are stored the longest. Recently added items are the first to be removed.
The reason why the stack is important is that it can reverse the order of items. Insertion and deletion are in reverse order.
The most typical example is that every web browser has a back button. When you browse the web, the web pages are placed in a stack (actually the URL of the web page). The page you are viewing now is at the top, and the page you were first viewing is at the bottom. If you press the 'Back' button, you will browse the previous pages in reverse order.
Python implementation stack
# 创建一个空的新栈。 它不需要参数,并返回一个空栈。 class Stack: def __init__(self): self.items = [] # 测试栈是否为空。不需要参数,并返回布尔值。 def isEmpty(self): return self.items == [] # 将一个新项添加到栈的顶部。它需要 item 做参数并不返回任何内容。 def push(self, item): self.items.append(item) # 从栈中删除顶部项。它不需要参数并返回 item 。栈被修改。 def pop(self): return self.items.pop() # 从栈返回顶部项,但不会删除它。不需要参数。 不修改栈。 def peek(self): return self.items[len(self.items)-1] # 返回栈中的 item 数量。不需要参数,并返回一个整数。 def size(self): return len(self.items)
Convert decimal number to arbitrary base number
I know the stack Just do a small project to practice the basic operation. Convert a decimal number to any base number. In fact, the highest number is hexadecimal (are there any higher bases?).
def baseConverter(n, base): # n是输入的十进制数字,base为要转化的进制数 digits = '0123456789ABCDEF' #创建一个新栈 s= Stack() # 将每次计算所得的余数添加进栈 while n> 0: rem = n % base s.push(rem) n = n // base # 将余数倒序排列至新字符串 newString = '' while not remstack.isEmpty(): newString = newString + digits[remstack.pop()] return newString
Related recommendations: "Python Tutorial"
The above is the detailed content of What does the stack in python refer to?. For more information, please follow other related articles on the PHP Chinese website!