< Back

Post Lab 25

Tracing Stacks

Draw the state of the stack at the end of each of these blocks of code. If there is an error in the code, please write Error.

  1.       my_stack = Stack()
    
          for i in range(5):
              my_stack.push(i)
    
          my_stack.pop()
          my_stack.pop()
        
  2.       my_stack = Stack()
    
          for i in range(5):
              my_stack.push(i)
    
          my_stack.pop()
    
          for i in range(5, 10):
              my_stack.push(i)
    
          my_stack.pop()
          my_stack.pop()
          my_stack.pop()
        
  3.       my_stack = Stack()
    
          for i in range(10):
              if i % 2 == 0:
                  my_stack.push(i)
              else:
                  my_stack.pop()
        
  4.       my_stack = Stack()
    
          for i in range(10):
              if i % 2 == 0:
                  my_stack.push(i)
              else:
                  removed_value = my_stack.pop()
                  my_stack.push(removed_value)
    
        
  5.       my_stack = Stack()
    
          for i in range(10):
              if i % 2 == 0:
                  my_stack.push(i)
              elif i % 3 == 0:
                  my_stack.pop()
              else:
                  removed_value = my_stack.pop()
                  my_stack.push(removed_value)
        
  6.       my_stack = Stack()
    
          for i in range(10):
              my_stack.push(i)
    
          while my_stack.peek() != 5:
              my_stack.push(my_stack.pop())
    
        
  7.       my_stack = Stack()
    
          for i in range(10):
              my_stack.push(i)
    
          while my_stack.peek() != 5:
              if my_stack.peek() % 2 == 0:
                  my_stack.push(my_stack.pop())
              else:
                  my_stack.pop()
    
        
  8.       my_stack = Stack()
          temp_list = []
          for i in range(10):
              my_stack.push(i)
    
          for j in range(5):
              temp_list.append(my_stack.pop())
    
          for item in temp_list:
              my_stack.push(item)
        

Submission

Bring this completed worksheet with you to the beginning of class on Friday.

Post labs are to be done individually. Sharing files between students is not allowed. Doing so is an Academic Integrity violation, and will be treated as such.