Skip to content

Commit 2500f4d

Browse files
three in one stack
1 parent 2732702 commit 2500f4d

File tree

1 file changed

+85
-0
lines changed
  • Python/chapter03/3.1 - Three in One

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/python3
2+
3+
import unittest
4+
5+
6+
def breakIntoThrees(arr):
7+
if len(arr) <= 2:
8+
print('Cannot break into 3 pieces')
9+
return
10+
11+
print('Breaking array into three pieces', arr)
12+
breakpoint = len(arr) // 3
13+
s1, s2, s3 = Stack(), Stack(), Stack()
14+
inputIntoThrees(s1, arr[:breakpoint])
15+
inputIntoThrees(s2, arr[breakpoint:breakpoint * 2])
16+
inputIntoThrees(s3, arr[breakpoint * 2:])
17+
return s1, s2, s3
18+
19+
20+
def inputIntoThrees(dastack, arr):
21+
print('Creating a new stack')
22+
for x in arr:
23+
dastack.push(x)
24+
print()
25+
26+
27+
class Stack:
28+
def __init__(self):
29+
self.stack = []
30+
31+
def pop(self):
32+
if not self.length:
33+
print('No stack to pop')
34+
return
35+
36+
item = self.stack.pop()
37+
print('Item popped', item)
38+
return item
39+
40+
def length(self):
41+
return len(self.stack)
42+
43+
def push(self, value):
44+
self.stack.append(value)
45+
print('Item added to stack', value)
46+
47+
def peek(self):
48+
if not self.length:
49+
print('No stack to peek')
50+
return
51+
print('Peeking into stack', self.stack[-1])
52+
53+
def printStack(self):
54+
if not self.length:
55+
print('No stack to peeek')
56+
return
57+
58+
print("Top of stack\n _ ")
59+
for x in self.stack[::-1]:
60+
print('|', x, '|')
61+
print('|', '_', '|')
62+
63+
64+
class Test(unittest.TestCase):
65+
@classmethod
66+
def setUpClass(cls):
67+
pass
68+
69+
@classmethod
70+
def tearDownClass(cls):
71+
pass
72+
73+
def test1(self):
74+
arr = [2, 5, 7, 10, 3, -1]
75+
s1, s2, s3 = breakIntoThrees(arr)
76+
s1.printStack()
77+
s2.printStack()
78+
s3.printStack()
79+
80+
arr1 = [2, 1, 4, 4, 6, 6, 6]
81+
s3, s4, s5 = breakIntoThrees(arr1)
82+
s5.printStack()
83+
84+
if __name__ == '__main__':
85+
unittest.main()

0 commit comments

Comments
 (0)