I am trying to make a loop that if the program sees a letter
or number
it will push(x) into a new list and if it sees an asterisk * it must pop(). It is more of a stack algorithm where the first letter or number in is the last one out. FILO First in last out
For example
If the program is given the following array
JavaScript
x
2
1
inputVals = ["1", "2" ,"*" ,"3", "4", "*" ,"*", "*" ,"5", "6"]
2
It should output
JavaScript
1
2
1
outputVal = ["2" ,"4", "3" ,"1"]
2
or a letter input
JavaScript
1
2
1
inputLetter = ["f" ,"a", "*", "d" ,"e" ,"t" ,"*" ,"o", "*" ,"*" ,"*" ,"*"]
2
letter Output
JavaScript
1
2
1
outPutLetter = ["a" ,"t", "o", "e" ,"d" ,"f"]
2
How can I implement this?
Advertisement
Answer
This should work:
JavaScript
1
13
13
1
def foo(input_list):
2
result = []
3
stack = []
4
for i in input_list:
5
if i == "*":
6
result.append(stack.pop())
7
else:
8
stack.append(i)
9
return result
10
11
print(foo(["1", "2" ,"*" ,"3", "4", "*" ,"*", "*" ,"5", "6"]))
12
print(foo(["f" ,"a", "*", "d" ,"e" ,"t" ,"*" ,"o", "*" ,"*" ,"*" ,"*"]))
13
['2', '4', '3', '1'] ['a', 't', 'o', 'e', 'd', 'f']