forked from Neterukun1993/purely-functional-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bankers_deque.py
75 lines (62 loc) · 2.51 KB
/
bankers_deque.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
from __future__ import annotations
from typing import TypeVar, Generic, Optional
from src.basic.stream import Stream # type: ignore
T = TypeVar('T')
class BankersDeque(Generic[T]):
fsize: int
f: Stream[T]
rsize: int
r: Stream[T]
def __init__(self,
fsize: int = 0, f: Optional[Stream[T]] = None,
rsize: int = 0, r: Optional[Stream[T]] = None) -> None:
self.fsize = fsize
self.f = Stream() if f is None else f
self.rsize = rsize
self.r = Stream() if r is None else r
def __bool__(self) -> bool:
return self.fsize + self.rsize != 0
def _check(self) -> BankersDeque[T]:
if self.fsize > 2 * self.rsize + 1:
i = (self.fsize + self.rsize) // 2
j = self.fsize + self.rsize - i
f = self.f.take(i)
r = self.r.concat(self.f.drop(i).reverse())
return BankersDeque[T](i, f, j, r)
elif self.rsize > 2 * self.fsize + 1:
j = (self.fsize + self.rsize) // 2
i = self.fsize + self.rsize - j
r = self.r.take(j)
f = self.f.concat(self.r.drop(j).reverse())
return BankersDeque[T](i, f, j, r)
return self
def cons(self, value: T) -> BankersDeque[T]:
return BankersDeque[T](self.fsize + 1, self.f.cons(value),
self.rsize, self.r)._check()
def head(self) -> T:
if not self:
raise IndexError("head from empty deque")
head: T = self.r.head() if self.fsize == 0 else self.f.head()
return head
def tail(self) -> BankersDeque[T]:
if not self:
raise IndexError("tail from empty deque")
if self.fsize == 0:
return BankersDeque()
return BankersDeque[T](self.fsize - 1, self.f.tail(),
self.rsize, self.r)._check()
def snoc(self, value: T) -> BankersDeque[T]:
return BankersDeque[T](self.fsize, self.f,
self.rsize + 1, self.r.cons(value))._check()
def last(self) -> T:
if not self:
raise IndexError("last from empty deque")
last: T = self.f.head() if self.rsize == 0 else self.r.head()
return last
def init(self) -> BankersDeque[T]:
if not self:
raise IndexError("init from empty deque")
if self.rsize == 0:
return BankersDeque()
return BankersDeque[T](self.fsize, self.f,
self.rsize - 1, self.r.tail())._check()