Advertisement
Lyuben_Andreev

Stack

Aug 27th, 2024
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | Source Code | 0 0
  1. class Stack:
  2.     def __init__(self):
  3.         self.stack = []
  4.  
  5.     def push(self, item):
  6.         self.stack.append(item)
  7.         print(f'Pushed {item} onto stack')
  8.  
  9.     def pop(self):
  10.         if not self.is_empty():
  11.             removed_item = self.stack.pop()
  12.             print(f'Popped {removed_item} from stack')
  13.             return removed_item
  14.         else:
  15.             print('Stack is empty')
  16.             return None
  17.  
  18.     def peek(self):
  19.         if not self.is_empty():
  20.             print(f'Top element is {self.stack[-1]}')
  21.             return self.stack[-1]
  22.  
  23.     def is_empty(self):
  24.         return len(self.stack) == 0
  25.  
  26.     def size(self):
  27.         return len(self.stack)
  28.  
  29.  
  30. def reverse_string(input_str):
  31.     stack = Stack()
  32.     for char in input_str:
  33.         stack.push(char)
  34.  
  35.     reversed_string = ''
  36.     while not stack.is_empty():
  37.         reversed_string += stack.pop()
  38.  
  39.     return reversed_string
  40.  
  41.  
  42. def is_balanced(expression):
  43.     stack = Stack()
  44.     for char in expression:
  45.         if char in '({[':
  46.             stack.push(char)
  47.         elif char in ')}]':
  48.             if stack.is_empty():
  49.                 return False
  50.             top = stack.pop()
  51.             if (char == ')' and top != '(') or \
  52.                     (char == '}' and top != '{') or \
  53.                     (char == ']' and top != '['):
  54.                 return False
  55.  
  56.     return stack.is_empty()
  57.  
  58.  
  59. my_string = reverse_string('Hello, World!')
  60. print(my_string)
  61.  
  62. my_stack = Stack()
  63. my_stack.push(1)
  64. my_stack.push(2)
  65. my_stack.push(3)
  66. my_stack.peek()
  67. my_stack.pop()
  68. my_stack.pop()
  69. my_stack.pop()
  70. my_stack.pop()
  71.  
  72. # “(){}[]”
  73. # “[({})]”
  74. # “({[()]})”
  75. # “({[}])”
  76. # “(((())))”
  77. # “([)]”
  78. # “{[()()]}”
  79. # “[(])”
  80. # “{{{{[[[]]]]}}}”
  81. # “{{[[(())]]}}”
  82. # “([{}])({})”
  83. # “{{[[(())]]]}”
  84.  
  85. print(is_balanced('{{[[(())]]]}'))
  86.  
  87.  
  88.  
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement