Workshop #3: Stacks

  • __len__
  • __bool__
  • __repr__
  • __str__
  • __contains__
In [82]:
class Stack:
    def __init__(self):
        self.items = []  # or, use 'list()'
        
    def is_empty(self):
        return self.items == []
    
    def size(self):
        return len(self.items)
    
    def peek(self):
        if len(self.items):
            return self.items[-1]
        else:
            return None

    def push(self, item):
        self.items.append(item)
        
    def pop(self):
        return self.items.pop()
    
    def __len__(self):
        return len(self.items)
        # alternatively, use def size
        # return self.size()
        
    def __bool__(self):
        return self.items == []
        #return not self.is_empty()
        
    def __str__(self):
        returnVal = "<Stack: ["
        for item in self.items:
            returnVal += str(item) + ", "
        returnVal += "]>"
        return returnVal
        
    def __repr__(self):
        return "Stack()"
    
    def __contains__(self, item):
        return item in self.items
In [83]:
s = Stack()

s.push(1)
s.push(2)
s.push(3)
In [84]:
s  # evaluation
Out[84]:
Stack()
In [85]:
print(s)  # coercion to string type
<Stack: [1, 2, 3, ]>
In [60]:
l = [1,2,3,4]

if l:
    print("list is not empty!")
list is not empty!
In [61]:
bool(l)
Out[61]:
True
In [62]:
l
Out[62]:
[1, 2, 3, 4]
In [63]:
r = range(10)
In [64]:
r
Out[64]:
range(0, 10)
In [65]:
s
Out[65]:
Stack()
In [66]:
s.is_empty()
Out[66]:
False
In [67]:
len(s)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-67-c71df1a6e151> in <module>
----> 1 len(s)

TypeError: object of type 'Stack' has no len()
In [68]:
7 in s
Out[68]:
False
In [69]:
3 in s
Out[69]:
True
In [70]:
x = 10
In [71]:
x
Out[71]:
10
In [72]:
x.__repr__()
Out[72]:
'10'
In [74]:
z = 10
In [75]:
l = [1,2,3]
In [76]:
l
Out[76]:
[1, 2, 3]
In [77]:
l.__repr__()
Out[77]:
'[1, 2, 3]'
In [78]:
r = range(10)
In [79]:
for i in r:
    print(i)
0
1
2
3
4
5
6
7
8
9
In [80]:
r
Out[80]:
range(0, 10)
In [81]:
r2 = range(0, 10)