Juanvulcano
Juanvulcano

Reputation: 1396

Appending correctly

I must define a function that takes in a list of strings. Push, pop and peek.

def digit_stack(commands):
    stack = []
    sums = 0
    for i in commands:
        if "PUSH" in i:
            for n in i:
                if n.isdigit():
                    stack.append(int(n))
        return stack

However

digit_stack("PUSH 3", "PUSH 4") == [3]

Why it is just appending the first push?

Upvotes: 2

Views: 41

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

You return after the first iteration:

for i in commands:
    if "PUSH" in i:
        for n in i:
            if n.isdigit():
                stack.append(int(n))
return stack # move outside the loop

Upvotes: 3

Related Questions