Last active
April 25, 2020 22:11
-
-
Save jameshih/3448d52850a40ecbacd8403ab3afed72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# define a Stack data structure | |
class Stack: | |
def __init__(self): | |
self.items = [] | |
def push(self,item): | |
self.items.append(item) | |
def pop(self): | |
return self.items.pop() | |
def peek(self): | |
return self.items[len(self.items)-1] | |
def size(self): | |
return len(self.items) | |
# solution for question 1 | |
def Stack1(): | |
s = Stack() | |
actions = list("A*BCE**F*GH***I*") | |
result = [] | |
for i in actions: | |
if i == "*": | |
s.pop() | |
continue | |
s.push(i) | |
print("Stack1 solution:",result) | |
# solution for question 2 | |
# since we have the input and output data predefined | |
# we can use dynamic programming and reverse engineer | |
# from the output data to get the list of actions | |
def Stack2(): | |
s = Stack() | |
actions = [] | |
res = [] | |
start = list("ABCDEF") | |
end = list("BADECF") | |
counter = len(start) | |
while len(res)!= counter: | |
if s.size() > 0 and s.peek() == end[0]: | |
res.append(s.pop()) | |
actions.append("pop") | |
end.pop(0) | |
continue | |
s.push(start.pop(0)) | |
actions.append("push") | |
print("Stack2 soultion:") | |
print(actions) | |
Stack1() | |
Stack2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment