From the course: Python Data Structures and Algorithms

Solution: Reverse a string using a stack - Python Tutorial

From the course: Python Data Structures and Algorithms

Solution: Reverse a string using a stack

(upbeat music) - So here's a solution to the stack challenge. Obviously there's many ways of doing this, but what I'm going to do is, for char, that's short for character in string. So that means for every character in my string, then I'm going to push. So I'm going to do S dot push. So S is my stack. I created on line 11. S dot push char. So this will then in turn, take each character and put it onto the stack. So it will take G N I N R A L, and put them all onto the stack G first, that capital L at the end last. So that's creating the stack with all the characters on and then using a wall loop. While not S dot is empty. We're going to build our reverse string. That's our result string, the string. And I'm going to use plus equals you could do reverse string equals reverse string plus, but this is just a shorthand for that. Now he has reversed string plus equals S dot pop. Now that should do the trick. Let's run it and see, learned a lot with LinkedIn learning is the solution. Okay, so just talk you through what we did there. So we added each of our characters from our string intern to our stack, and then we had this condition. So while there was anything left in the stack, we kept on looping and we built our solution string by popping items in turn off of our stack. Two different types of iteration here, we had conditional iteration, that's the wild type and we had four. And the basic distinction is if you know how many times you want to do something; you tend to use four. And we do know how many times because we have a set number of characters in our string, but then while the program doesn't know how long or how big the stack is at this point. So we just say, well, it's not empty on line seventeen. So there is a solution to the challenge.

Contents