Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: 8:
Дальше: 10:

Chapter 9

These are the solutions to the exercises found in the section .

  1. Presumably, we’d want to be nice to the callers and answer their phone calls in the order in which they were received. For this, we’d use a queue, which processes data FIFO (first in, first out).

  2. We’d be able to read the 4, which is now the top element in the stack. This is because we’ll have popped the 6 and the 5, which were previously sitting on top of the 4.

  3. We’d be able to read the 3, which is now at the front of the queue, after having dequeued the 1 and the 2.

  4. We can take advantage of the stack because of the fact that we pop each item in the reverse order of which they were pushed onto the stack. So we’ll first push each character of the string onto the stack. Then we’ll pop each one off while adding them to the end of a new string:

     import​ ​stack​ ​as​ ​stack_module
     
     
     def​ ​reverse​(string):
      stack = stack_module.Stack()
      new_string = ​""
     
     for​ char ​in​ string:
      stack.push(char)
     
     while​ stack.read():
      new_string += stack.pop()
     
     return​ new_string

    The stack_module referred to here is simply our homegrown Stack implementation from Chapter 9, which we’ve saved in a file called stack.py.

Назад: 8:
Дальше: 10: