Skip to content

Commit

Permalink
Added NEW MODULES in DataStax Library
Browse files Browse the repository at this point in the history
  • Loading branch information
warmachine028 committed Dec 27, 2021
1 parent 5a52cc7 commit bd66681
Show file tree
Hide file tree
Showing 23 changed files with 632 additions and 63 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### MyExtra ###
.Box_Drawing_Symbols.txt
desktop.ini

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down
40 changes: 27 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@

## What's New?

- Added terminal demo
- Improved type hinting using mypy static type checker
- Removed few bugs and potential errors
- Purified test_structure
- Improvised for uploading in PyPI
- Added Arrays
- Included Array Implementation of Stack
- Included Array Implementation of Queue
- Added LinkedList Implementation of Queue
- Added Heap Trees (Max Heap and Min Heap)

## Table of Contents

Expand Down Expand Up @@ -65,12 +65,10 @@

## Installation

1. Clone this repository locally
2. Reach base folder _datastax/_
3. Use the python package manager [pip](https://pip.pypa.io/en/stable/) to install datastax.
1. Use the python package manager [pip](https://pip.pypa.io/en/stable/) to install datastax.

```bash
pip install .
pip install -i https://test.pypi.org/simple/ datastax
```

## Usage
Expand All @@ -93,12 +91,14 @@ pip install .
Available modules are:
1. LinkedLists
2. Trees
Usage
$ py datastax <data-structure> [data]
Data Structures:
trees Hierarchical DS
linkedlists Linear DS
-> trees Hierarchical DS
-> linkedlists Linear DS
-> arrays Fixed Size Linear DS
```
- Then follow as the instruction guides

Expand Down Expand Up @@ -130,5 +130,19 @@ print(bt)
┌──┴──┐
4 5
"""
```
---------------------------------------------------
from datastax.trees import MinHeapTree
MiHT = MinHeapTree([1, 2, 4, 2, 6, 5, 9, 18, 3, 2])
print(MiHT)
## OUTPUT
"""
1
┌───────────┴───────────┐
2 4
┌─────┴─────┐ ┌─────┴─────┐
2 2 5 9
┌──┴──┐ ┌──┘
18 3 6
"""
```
4 changes: 2 additions & 2 deletions datastax/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# __init__.py

# Versioning of the datastax package
__version__ = "0.0.2"
__all__ = ['trees', 'linkedlists']
__version__ = "0.0.3"
__all__ = ['trees', 'linkedlists', 'arrays']
21 changes: 16 additions & 5 deletions datastax/__main__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import sys

from datastax import linkedlists as ll, trees
from datastax import linkedlists as ll, trees, arrays


def main():
if len(sys.argv) > 1:
data_structure = sys.argv[1].lower()
data = sys.argv[2:] if len(sys.argv) > 2 else [*range(5)] # take User given data or default
if data_structure in ('linkedlist', "linkedlists"):
if data_structure in ('array', 'arrays'):
queue = arrays.Queue(len(data))
stack = arrays.Stack(len(data))
for i in data:
stack.push(i)
queue.enqueue(i)
print("Visuals for Arrays:\n\n"
f"1. Stack: \n{stack}\n\n"
f"2. Queue: \n{queue}\n\n")
elif data_structure in ('linkedlist', "linkedlists"):
print("Visuals for LinkedLists:\n\n"
f"1. Singly Linked List: \n{ll.LinkedList(data)}\n\n"
f"2. Doubly Linked List: \n{ll.DoublyLinkedList(data)}\n\n"
f"3. Circular Linked List: \n{ll.CircularLinkedList(data)}\n\n"
f"4. Doubly Circular List: \n{ll.DoublyCircularList(data)}\n\n")
f"4. Doubly Circular List: \n{ll.DoublyCircularList(data)}\n\n"
f"5. Queue: \n{ll.Queue(data)}\n\n")
elif data_structure in ('tree', 'trees'):
print("Visuals for Trees:\n\n"
f"1. Binary Tree \n{trees.BinaryTree(data)}\n\n"
Expand All @@ -27,8 +37,9 @@ def main():
"\nUsage\n"
"$ py datastax <data-structure> [data]\n"
"Data Structures: \n"
" trees Hierarchical DS\n"
" linkedlists Linear DS")
"-> trees Hierarchical DS\n"
"-> linkedlists Linear DS\n"
"-> arrays Fixed Size Linear DS")


if __name__ == '__main__':
Expand Down
7 changes: 7 additions & 0 deletions datastax/arrays/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from .queue import Queue
from .stack import Stack

__all__ = [
'Queue',
'Stack'
]
69 changes: 69 additions & 0 deletions datastax/arrays/queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Queue Implementation using Lists (Pseudo Arrays)
import math
from typing import Any, Union


class Queue:
def __init__(self, capacity: int = None):
self._capacity = capacity if capacity is not None else math.inf
self._array: list[Any] = []
self._front = self._rear = 0

@property
def array_repr(self) -> list[Any]:
return self._array[self._front:self._rear]

def is_full(self) -> bool:
return len(self._array) == self._capacity

def is_empty(self) -> bool:
return not len(self._array)

def enqueue(self, item: Any) -> int:
if self.is_full():
print("WARNING: THE QUEUE IS ALREADY FULL, CANT ENQUEUE ANY FURTHER")
return -1
self._array.append(item)
self._rear += 1
return 0

def dequeue(self) -> Union[int, Any]:
if self.is_empty() or self._front >= self._rear:
print("WARNING: THE QUEUE IS ALREADY EMPTY, CANT DEQUEUE ANY FURTHER")
return -1
deleted_item = self._array[self._front]
self._front += 1
return deleted_item

def peek(self) -> str:
if self.is_empty() or self._front >= self._rear: return "QUEUE EMPTY"
return str(self._array[self._front])

def __str__(self):
if self.is_empty(): return '┌───────────────────┐\n' \
'│ QUEUE EMPTY │\n' \
'└───────────────────┘'
padding = 4
max_breadth = max(len(str(item)) for item in self._array) + padding
middle_part = 'FRONT -> │'
upper_part = f"{' ' * (len(middle_part) - 1)}┌"
lower_part = f"{' ' * (len(middle_part) - 1)}└"
if self._front: # Representing Garbage Values with '╳'
for _ in self._array[:self._front]:
middle_part += f"{'╳'.center(max_breadth)}│"
upper_part += f"{'─' * max_breadth}┬"
lower_part += f"{'─' * max_breadth}┴"
upper_part = upper_part[:-1] + '╥'
middle_part = middle_part[:-1] + '║'
lower_part = lower_part[:-1] + '╨'
for item in self._array[self._front:]:
middle_part += f'{str(item).center(max_breadth)}│'
upper_part += f"{'─' * max_breadth}┬"
lower_part += f"{'─' * max_breadth}┴"
upper_part = f"{upper_part[:-1]}{'╖' if len(self._array) == self._front else '┐'}\n"
middle_part += ' <- REAR\n'
lower_part = f"{lower_part[:-1]}{'╜' if len(self._array) == self._front else '┘'}\n"
return upper_part + middle_part + lower_part

def __repr__(self):
return self.__str__()
56 changes: 56 additions & 0 deletions datastax/arrays/stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Stack Implementation using Lists (Pseudo Arrays)
import math
from typing import Any, Union


class Stack:
def __init__(self, capacity: int = None):
self.capacity = capacity if capacity is not None else math.inf
self._array: list[Any] = []

@property
def array(self):
return self._array

def is_full(self) -> bool:
return len(self._array) == self.capacity

def is_empty(self) -> bool:
return not len(self._array)

def push(self, item: Any) -> int:
if self.is_full(): # Overflow Condition
print('OVERFLOW WARNING: ATTEMPTED PUSH OPERATION IN FULL STACK')
return -1
self._array.append(item)
return 0

def pop(self) -> Union[int, Any]:
if self.is_empty(): # Underflow Condition handled
print('UNDERFLOW WARNING: ATTEMPTED POP OPERATION FROM EMPTY STACK')
return -1
return self._array.pop()

def peek(self) -> str:
return 'STACK EMPTY' if self.is_empty() else self._array[-1]

def __str__(self):
if self.is_empty(): return '│STACK EMPTY│\n' \
'╰───────────╯\n'
padding = 9
maximum_breadth = (max(len(str(item)) for item in self._array)) + padding
if self.is_full(): string = f"┌{'─' * maximum_breadth}\n" # For FULLY LOADED STACK
elif (len(self._array) < 0.7 * self.capacity) or (self.capacity - len(self._array) > 5):
string = f"│{' ' * maximum_breadth}\n" \
f":{' ' * maximum_breadth}:\n" # Shrink visualization
else: string = f"│{' ' * maximum_breadth}\n" * 2 * (self.capacity - len(self._array)) # Expand Visualization

for n, item in enumerate(self._array[::-1]):
top = '' if self.is_full() and not n else f"├{'─' * maximum_breadth}\n"
bottom = f"│{str(item).center(maximum_breadth)}{'<- TOP' if not n else ''}\n"
string += top + bottom
string += f"╰{'─' * maximum_breadth}\n"
return string

def __repr__(self):
return self.__str__()
4 changes: 3 additions & 1 deletion datastax/linkedlists/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
from .doubly_circular_list import DoublyCircularList
from .doubly_linked_list import DoublyNode, DoublyLinkedList
from .linked_list import LinkedList, Node
from .queue import Queue

__all__ = [
'LinkedList', 'Node',
'DoublyLinkedList', 'DoublyNode',
'CircularLinkedList',
'DoublyCircularList'
'DoublyCircularList',
'Queue'
]
19 changes: 0 additions & 19 deletions datastax/linkedlists/linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,3 @@ def __str__(self, head: Node = None):

def __repr__(self):
return self.__str__()


# __main__
if __name__ == '__main__':
LL = LinkedList()
print(LL)
LL.insert(10)
LL.insert(11)
LL.append(90)
LL.insert(199)
LL.append(109)
print(LL)

D = LinkedList([*range(5)])
D.insert(10)
D.insert(20)
D.append(199)
print(D)
# print(D.__str__(True))
85 changes: 85 additions & 0 deletions datastax/linkedlists/queue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Queue implementation using LinkedLists
from __future__ import annotations

from sys import maxsize
from typing import Any, Optional, Union

from datastax.linkedlists.linked_list import LinkedList, Node


class Queue(LinkedList):
def __init__(self, array: list[Any] = None, capacity: int = None):
super().__init__()
self._rear = 0
if capacity is not None and capacity < 0:
print("Capacity can't be negative"
"Setting unbounded capacity")
self._capacity = capacity if capacity is not None and capacity > 0 else maxsize
if array and array[0] is not None:
for item in array[:self._capacity]:
self.enqueue(item)

def is_empty(self) -> bool:
return self.head is None

def is_full(self) -> bool:
return self._rear == self._capacity

def enqueue(self, data: Any) -> int:
if self.is_full():
print("WARNING: THE QUEUE IS ALREADY FULL, CANT ENQUEUE ANY FURTHER")
return -1
super().append(data)
self._rear += 1
return 0

def dequeue(self) -> Union[int, Any]:
if self.is_empty():
print("WARNING: THE QUEUE IS ALREADY EMPTY, CANT DEQUEUE ANY FURTHER")
return -1
# Dequeue Operation
deleted_node = self.head
deleted_item = deleted_node.data
self._head = self.head.next
self._rear -= 1
return deleted_item

def peek(self) -> str:
if self.is_empty(): return "QUEUE EMPTY"
return str(self._tail.data if self._tail else None)

def append(self, data: Any) -> None:
print("WARNING: Method not available here.")

def insert(self, data: Any) -> None:
print("WARNING: Method not implemented here."
"Please use enqueue method to insert")

def __str__(self, head: Node = None):
def maximum_breadth(ref: Optional[Node]) -> int:
result = 0
while ref:
result = max(len(str(ref.data)), result)
ref = ref.next
return result

if self.is_empty(): return '╔═══════════════════╗\n' \
'║ QUEUE EMPTY ║\n' \
'╚═══════════════════╝'
padding = 4
max_breadth = maximum_breadth(self.head) + padding
middle_part = 'FRONT -> '
upper_part = f"{' ' * (len(middle_part) - 1)} "
lower_part = f"{' ' * (len(middle_part) - 1)} "
temp = self.head
while temp:
item = temp.data
upper_part += f"╔{'═' * max_breadth}╗ "
middle_part += f'║{str(item).center(max_breadth)}║ <-'
lower_part += f"╚{'═' * max_breadth}╝ "
temp = temp.next
upper_part = f"{upper_part[:-1]}\n"
middle_part += ' REAR\n'
lower_part = f"{lower_part[:-1]}\n"

return upper_part + middle_part + lower_part
Loading

0 comments on commit bd66681

Please sign in to comment.