Digit Stack
In computer science, a stack is a particular kind of data type or collection in which the principal operations in the collection are the addition of an entity to the collection (also known as push) and the removal of an entity (also known as pop). The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. In a LIFO data structure, the last element added to the structure must be the first one to be removed. Often a peek, or top operation is also implemented, returning the value of the top element without removing it.
We will emulate the stack process with Python. You are given a sequence of commands:
- "PUSH X" -- add X in the stack, where X is a digit.
- "POP" -- look and remove the top position. If the stack is empty, then it returns 0 (zero) and does nothing.
- "PEEK" -- look at the top position. If the stack is empty, then it returns 0 (zero).
The stack can only contain digits.
You should process all commands and sum all digits which were taken from the stack ("PEEK" or "POP"). Initial value of the sum is 0 (zero).
Let's look at an example, here’s the sequence of commands:
["PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"]
Input: A sequence of commands as a list of strings.
Output: The sum of the taken digits as an integer.
题目大义: 使用Python模拟一个栈, 有PUSH, POP, PEEK命令, PEEK命令返回栈顶元素, POP命令返回并删除栈顶元素, PUSH命令将数字压入栈中
def digit_stack(commands):
sim_stack = []
total = 0
for each in commands:
if each[1] == 'U': #push
pos = each.index(' ')
sim_stack.append(int(each[pos + 1:]))
else:
if sim_stack:
total += sim_stack[-1] if each[1] == 'O': #pop
sim_stack.pop() return total
因为只有三个命令, 且命令的第二个字母不同, 所以以其区分命令
观摩cdthurman的代码
def digit_stack(commands):
stack, sum = [],0
for cmd in commands:
if 'PUSH' in cmd.upper():
stack.append(int(cmd.strip()[-1]))
elif 'POP' in cmd.upper() and len(stack):
sum += stack.pop()
elif len(stack):
sum+=stack[-1]
return sum
使用了in, 无他