Advertisement
575

Class Stack

575
Sep 23rd, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. class Stack:
  2.      def __init__(self):
  3.           self.items = []
  4.      
  5.      def isEmpty(self):
  6.           return self.items == []
  7.      
  8.      def push(self, item):
  9.           self.items.append(item)
  10.              
  11.      def rpush(self, item):
  12.           self.items.append(item)
  13.           return self
  14.      
  15.      def pop(self):
  16.           return self.items.pop()
  17.      
  18.      def penultimate_element(self):
  19.           return self.items[len(self.items) - 1]
  20.      
  21.      def size(self):
  22.           return len(self.items)
  23.      
  24.      def __str__(self):
  25.           return str(self.items)
  26.      
  27.      def __add__(self, other):
  28.           if type(other) is int or type(other) is float:
  29.                return self.rpush(other)
  30.           elif type(other) is type(self):
  31.                for i in range(len(other.items)):
  32.                     self.push(other.items[i])
  33.                return self
  34.           else:
  35.                return 'ERROR'
  36.          
  37.      def clearall(self):
  38.           self.items.clear()
  39.          
  40.  
  41. stack1 = Stack()
  42. stack2 = Stack()
  43.  
  44. if stack1.isEmpty():
  45.      print('Empty')
  46.  
  47. stack1.push(1)
  48. stack1.push(2)
  49. stack1.push(3)
  50. stack1.push(4)
  51. stack2.push(2)
  52. stack2.push(2)
  53. stack2.push(2)
  54. stack2.push(2)
  55.  
  56. print(stack1.penultimate_element())
  57.  
  58. print(stack1)
  59. print(stack2)
  60.  
  61. result = stack1 + stack2
  62. print(result)
  63. print(type(result))
  64. result.clearall()
  65. print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement