Digit Stack

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命令将数字压入栈中

 1 def digit_stack(commands):
 2     sim_stack = []
 3     total = 0
 4     for each in commands:
 5         if each[1] == 'U':    #push
 6             pos = each.index(' ')
 7             sim_stack.append(int(each[pos + 1:]))
 8         else:
 9             if sim_stack:
10                 total += sim_stack[-1]
11 
12                 if each[1] == 'O':    #pop
13                     sim_stack.pop()
14 
15     return total

因为只有三个命令, 且命令的第二个字母不同, 所以以其区分命令

观摩cdthurman的代码

 1 def digit_stack(commands):
 2     stack, sum = [],0
 3     for cmd in commands:
 4         if 'PUSH' in cmd.upper():
 5             stack.append(int(cmd.strip()[-1]))
 6         elif 'POP' in cmd.upper() and len(stack):
 7             sum += stack.pop()
 8         elif len(stack):
 9             sum+=stack[-1]
10     return sum

使用了in, 无他

posted @ 2014-08-07 14:42  哲人善思  阅读(197)  评论(0编辑  收藏  举报