-
Notifications
You must be signed in to change notification settings - Fork 77
/
bag.py
47 lines (33 loc) · 901 Bytes
/
bag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Execution: python bag.py < input.txt
% more tobe.txt
to be or not to - be - - that - - - is
% python bag.py < tobe.txt
to be or not to - be - - that - - - is
"""
from algs4.utils.linklist import Node, LinkIterator
class Bag:
def __init__(self):
self.first = None
self.n = 0
def __str__(self):
return " ".join(str(i) for i in self)
def __iter__(self):
return LinkIterator(self.first)
def size(self):
return self.n
def is_empty(self):
return self.first is None
def add(self, item):
oldfirst = self.first
self.first = Node(item, oldfirst)
self.n += 1
if __name__ == '__main__':
import sys
for line in sys.stdin:
bag = Bag()
for item in line.split():
bag.add(item)
print("size of bag = ", bag.size())
for i in bag:
print(i)