The Self-Taught Computer Scientist
Download 1.48 Mb. Pdf ko'rish
|
books-library.net-11301817Az7X6
- Bu sahifa navigatsiya:
- Chapter 11
Data Structures
118 Otherwise, you remove the first item in your linked list and return it: poppednode = self.head self.head = self.head.next return poppednode.data Here is an example of creating a stack using this code and pushing and popping items on and off of it: stack = Stack() stack.push(1) stack.push(2) stack.push(3) for i in range(3): print(stack.pop()) >> 3 >> 2 >> 1 Finally, you can also use a Python list as a stack. Here is how it works: stack = [] print(stack) stack.append('Kanye West') print(stack) stack.append('Jay- Z') print(stack) stack.append('Chance the Rapper') print(stack) stack.pop() print(stack) >> [] >> ['Kanye West'] >> ['Kanye West', 'Jay- Z'] >> ['Kanye West', 'Jay- Z', 'Chance the Rapper'] >> ['Kanye West', 'Jay- Z'] Python’s lists come with the methods append and pop . The append method adds an item to the end of a list, which is the same as pushing an item onto a stack. The pop method removes an item from the end of a list. If you don’t specify which item to remove, it removes the last item. When you first print your stack, it is empty because you haven’t added anything to it yet. >> [] Chapter 11 Stacks 119 Next, you push three items— 'Kanye West' , 'Jay- Z' , and 'Chance the Rapper' — onto your stack with these lines of code: stack.append('Kanye West') stack.append('Jay- Z') stack.append('Chance the Rapper') Then, you pop the last element, 'Chance the Rapper' , off your stack, leaving the first two elements: stack.pop() That is why when you print your stack for the final time, 'Chance the Rapper' is missing: >> ['Kanye West', 'Jay- Z'] Of course, when you use a Python list as a stack, you are not limited to taking items off your stack in the order you put them on, so if you want to enforce that, you need to create a Stack class. Using Stacks to Reverse Strings A common interview question for Python jobs is to reverse a string three different ways. If you are familiar with Python, you know you can reverse a string like this: a_string[::- 1] or like this: ''.join(reversed('a string')) When it comes to reversing a string a third way, you may be stuck, however. The key is what you learned earlier in this chapter: you can use a stack to reverse a string because when you pop characters off a stack, they come off the stack in reverse order (see Figure 11.3). Download 1.48 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling