forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
switch_pairs.py
84 lines (76 loc) · 2.84 KB
/
switch_pairs.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
Given a stack, switch_pairs function takes a stack as a parameter and that
switches successive pairs of numbers starting at the bottom of the stack.
For example, if the stack initially stores these values:
bottom [3, 8, 17, 9, 1, 10] top
Your function should switch the first pair (3, 8), the second pair (17, 9), ...:
bottom [8, 3, 9, 17, 10, 1] top
if there are an odd number of values in the stack, the value at the top of the
stack is not moved: For example:
bottom [3, 8, 17, 9, 1] top
It would again switch pairs of values, but the value at the top of the stack (1)
would not be moved
bottom [8, 3, 9, 17, 1] top
Note: There are 2 solutions:
first_switch_pairs: it uses a single stack as auxiliary storage
second_switch_pairs: it uses a single queue as auxiliary storage
"""
import unittest
import collections
def first_switch_pairs(stack):
storage_stack = []
for i in range(len(stack)):
storage_stack.append(stack.pop())
for i in range(len(storage_stack)):
if len(storage_stack) == 0:
break
first = storage_stack.pop()
if len(storage_stack) == 0: # case: odd number of values in stack
stack.append(first)
break
second = storage_stack.pop()
stack.append(second)
stack.append(first)
return stack
def second_switch_pairs(stack):
q = collections.deque()
# Put all values into queue from stack
for i in range(len(stack)):
q.append(stack.pop())
# Put values back into stack from queue
for i in range(len(q)):
stack.append(q.pop())
# Now, stack is reverse, put all values into queue from stack
for i in range(len(stack)):
q.append(stack.pop())
# Swap pairs by appending the 2nd value before appending 1st value
for i in range(len(q)):
if len(q) == 0:
break
first = q.pop()
if len(q) == 0: # case: odd number of values in stack
stack.append(first)
break
second = q.pop()
stack.append(second)
stack.append(first)
return stack
class TestSuite(unittest.TestCase):
"""
test suite for the function (above)
"""
def test_switch_pairs(self):
# Test case: even number of values in stack
# bottom [3, 8, 17, 9, 1, 10] top
self.assertEqual([8, 3, 9, 17, 10, 1],
first_switch_pairs([3, 8, 17, 9, 1, 10]))
self.assertEqual([8, 3, 9, 17, 10, 1],
second_switch_pairs([3, 8, 17, 9, 1, 10]))
# Test case: odd number of values in stack
# bottom [3, 8, 17, 9, 1] top
self.assertEqual([8, 3, 9, 17, 1],
first_switch_pairs([3, 8, 17, 9, 1]))
self.assertEqual([8, 3, 9, 17, 1],
second_switch_pairs([3, 8, 17, 9, 1]))
if __name__ == "__main__":
unittest.main()