Skip to content
Advertisement

pushing and poping into new list

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

inputVals = ["1", "2" ,"*" ,"3", "4", "*" ,"*", "*" ,"5", "6"]

It should output

outputVal = ["2" ,"4", "3" ,"1"]

or a letter input

inputLetter = ["f" ,"a", "*", "d" ,"e" ,"t" ,"*" ,"o", "*" ,"*" ,"*" ,"*"]

letter Output

outPutLetter = ["a" ,"t", "o", "e" ,"d" ,"f"]

How can I implement this?

Advertisement

Answer

This should work:

def foo(input_list):
    result = []
    stack = []
    for i in input_list:
        if i == "*":
            result.append(stack.pop())
        else:
            stack.append(i)
    return result

print(foo(["1", "2" ,"*" ,"3", "4", "*" ,"*", "*" ,"5", "6"]))
print(foo(["f" ,"a", "*", "d" ,"e" ,"t" ,"*" ,"o", "*" ,"*" ,"*" ,"*"]))
['2', '4', '3', '1']
['a', 't', 'o', 'e', 'd', 'f']
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement