Skip to content

Commit 06e0145

Browse files
fifo
1 parent d262af8 commit 06e0145

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed

fifo/description.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# FIFO data structure
2+
3+
Implement a FIFO (first in, first out) data struture with O(1) push and O(1) pop operations, without using a libary or native implementation.
4+
5+
Given n sequential add and get operations, perform each operation in order.
6+
7+
## Example
8+
9+
### Input:
10+
11+
put 1
12+
put 2
13+
put 3
14+
pop
15+
pop
16+
pop
17+
18+
### Output:
19+
20+
1
21+
2
22+
3
23+
24+
## Run the program
25+
26+
In the folder run the command:
27+
28+
```
29+
python fifo.py
30+
```

fifo/fifo.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import unittest
2+
3+
4+
class FIFO:
5+
def __init__(self, size=5):
6+
self.list = [0] * size
7+
self.push_idx = 0
8+
self.pop_idx = 0
9+
10+
def push(self, val):
11+
self.list[self.push_idx] = val
12+
self.push_idx = (self.push_idx + 1) % len(self.list)
13+
14+
if self.push_idx == self.pop_idx:
15+
self.increase_lst_size()
16+
17+
def pop(self):
18+
if self.pop_idx == self.push_idx:
19+
return None
20+
21+
val = self.list[self.pop_idx]
22+
self.pop_idx = (self.pop_idx + 1) % len(self.list)
23+
24+
return val
25+
26+
def increase_lst_size(self):
27+
new_list = [0] * (len(self.list) * 2)
28+
new_list_idx = 0
29+
30+
for i in xrange(0, len(self.list)):
31+
idx = (self.push_idx + i) % len(self.list)
32+
new_list[new_list_idx] = self.list[idx]
33+
new_list_idx += 1
34+
35+
self.list = new_list
36+
self.push_idx = new_list_idx
37+
self.pop_idx = 0
38+
39+
40+
class FIFOTests(unittest.TestCase):
41+
def test_push_pop(self):
42+
fifo = FIFO()
43+
fifo.push(1)
44+
self.assertEqual(fifo.pop(), 1)
45+
46+
def test_increase_size(self):
47+
fifo = FIFO(2)
48+
fifo.push(1)
49+
fifo.push(2)
50+
self.assertEqual(len(fifo.list), 4)
51+
52+
def test_wrap(self):
53+
fifo = FIFO(3)
54+
fifo.push(1)
55+
fifo.push(2)
56+
fifo.pop()
57+
fifo.pop()
58+
fifo.push(3)
59+
fifo.push(4)
60+
self.assertEqual(len(fifo.list), 3)
61+
self.assertEqual(fifo.pop(), 3)
62+
self.assertEqual(fifo.pop(), 4)
63+
64+
65+
if __name__ == '__main__':
66+
unittest.main()

0 commit comments

Comments
 (0)