-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
data structures completed #4
Open
eoneoff
wants to merge
5
commits into
kottans:master
Choose a base branch
from
eoneoff:data-structures-http
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
2 changes: 2 additions & 0 deletions
2
submissions/eoneoff/data-structures-http/data_structures/__init__.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from .stack import Stack | ||
from .linked_list import LinkedList |
44 changes: 44 additions & 0 deletions
44
submissions/eoneoff/data-structures-http/data_structures/linked_list.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
from .node import Node | ||
|
||
class LinkedList: | ||
def __init__(self): | ||
self._root = None | ||
self._length = 0 | ||
|
||
def __iter__(self): | ||
current = self._root | ||
while current: | ||
yield current | ||
current = current.next | ||
|
||
def insert(self, value, successor = None): | ||
if(successor and self._root.value != successor): | ||
for node in self: | ||
if node.next and node.next.value == successor: | ||
node.next = Node(value, node.next) | ||
self._length+=1 | ||
return | ||
error_message = f'Value {successor} is not in the list' | ||
raise ValueError(error_message) | ||
else: | ||
self._root = Node(value, self._root) | ||
self._length+=1 | ||
|
||
def remove(self, value): | ||
if self._root.value == value: | ||
self._root = self._root.next | ||
self._length-=1 | ||
return | ||
for node in self: | ||
if node.next and node.next.value == value: | ||
node.next = node.next.next | ||
self._length-=1 | ||
return | ||
error_message = f'Value {value} is not in the list' | ||
raise ValueError(error_message) | ||
|
||
def show_list(self): | ||
return [node.value for node in self] | ||
|
||
def __len__(self): | ||
return self._length |
20 changes: 20 additions & 0 deletions
20
submissions/eoneoff/data-structures-http/data_structures/node.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
class Node: | ||
def __init__(self, value = None, next = None): | ||
self._value = value | ||
self._next = next | ||
|
||
@property | ||
def value(self): | ||
return self._value | ||
|
||
@value.setter | ||
def value(self, value): | ||
self._value = value | ||
|
||
@property | ||
def next(self): | ||
return self._next | ||
|
||
@next.setter | ||
def next(self, value): | ||
self._next = value |
21 changes: 21 additions & 0 deletions
21
submissions/eoneoff/data-structures-http/data_structures/stack.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from .node import Node | ||
|
||
class Stack: | ||
def __init__ (self): | ||
self._root = None | ||
self._length = 0 | ||
|
||
def push(self, value): | ||
self._root = Node(value, self._root) | ||
self._length+=1 | ||
|
||
def pop(self): | ||
if self._length: | ||
out = self._root.value | ||
self._root = (self._root or None) and self._root.next | ||
self._length-=1 | ||
return out | ||
else: return None | ||
|
||
def __len__(self): | ||
return self._length |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
"""Data structues with html assess | ||
|
||
The assess to data structues is provided through html requests | ||
|
||
stack | ||
<socket>/stack | ||
|
||
POST request with json object of format {"data":<value to push to stack>} pushes vaule to stack | ||
|
||
DELETE request pops a value from a stack and returns in in json object of format | ||
{"data": <value popped from stack} | ||
|
||
linked list | ||
<socket>/list | ||
|
||
GET request returns the contents of list in a json object | ||
|
||
POST request with json object of format | ||
{ | ||
"data": <value to insert into stack>[, | ||
"sucessor": <successor value>] | ||
} | ||
inserts value into list | ||
|
||
DELETE request with json object of format {"data":<value to remove from list>} removes | ||
the value from the list | ||
|
||
If data is not presented in json format, if it is not string or number or if a successor | ||
or an item to remove is not in the list a Bad Reques code is returned | ||
""" | ||
|
||
from data_structures import * | ||
from server import * | ||
|
||
DataServer(Stack, LinkedList).run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
from .server import DataServer |
84 changes: 84 additions & 0 deletions
84
submissions/eoneoff/data-structures-http/server/handler.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
from http.server import BaseHTTPRequestHandler | ||
import json | ||
import cgi | ||
|
||
class DataHandler(BaseHTTPRequestHandler): | ||
def __init__(self, stack, linked_list, *args): | ||
self._stack = stack | ||
self._list = linked_list | ||
super().__init__(*args) | ||
|
||
def _set_headers(self): | ||
self.send_response(200) | ||
self.send_header('Content-type', 'application/json') | ||
self.end_headers() | ||
|
||
def do_HEAD(self): | ||
self._set_headers() | ||
|
||
@staticmethod | ||
def _value_is_valid(value): | ||
return type(value) == str \ | ||
or type(value) == int \ | ||
or type(value) == float | ||
|
||
def _request_is_json(self): | ||
ctype,_ = cgi.parse_header(self.headers.get('content-type')) | ||
if ctype!='application/json': | ||
self.send_error(400, 'Wrong content type') | ||
return False | ||
else: return True | ||
|
||
def _get_request_data(self): | ||
length = int(self.headers.get('content-length')) | ||
return json.loads(self.rfile.read(length)) | ||
|
||
def _get_structure_type(self): | ||
structure_type = self.path.split('/')[1] | ||
return structure_type if structure_type in ['stack', 'list'] else None | ||
|
||
|
||
def do_GET(self): | ||
if(self._get_structure_type() == 'list'): | ||
self._set_headers() | ||
self.wfile.write(str.encode(json.dumps({'data':self._list.show_list()}))) | ||
|
||
def do_POST(self): | ||
if(self._request_is_json()): | ||
data = self._get_request_data() | ||
if DataHandler._value_is_valid(data['data']): | ||
structure_type = self._get_structure_type() | ||
if structure_type == 'stack': | ||
self._stack.push(data['data']) | ||
self.send_response(200) | ||
self.end_headers() | ||
elif structure_type == 'list': | ||
successor = data.setdefault('successor') | ||
if not successor or DataHandler._value_is_valid(successor): | ||
try: | ||
self._list.insert(data['data'], successor) | ||
self.send_response(200) | ||
self.end_headers() | ||
except ValueError as err: | ||
self.send_error(400, str(err)) | ||
else: self.send_error(400, 'Wrong successor format') | ||
else: self.send_error(400, 'Wrong value type') | ||
else: self.send_error(400, 'Wrong content type') | ||
|
||
def do_DELETE(self): | ||
structure_type = self._get_structure_type() | ||
if structure_type == 'stack': | ||
self._set_headers() | ||
self.wfile.write(str.encode(json.dumps({'data': self._stack.pop()}))) | ||
elif structure_type == 'list': | ||
if self._request_is_json(): | ||
data = self._get_request_data() | ||
if DataHandler._value_is_valid(data['data']): | ||
try: | ||
self._list.remove(data['data']) | ||
self.send_response(200) | ||
self.end_headers() | ||
except ValueError as err: | ||
self.send_error(400, str(err)) | ||
else: self.send_error(400, 'Wrong data type') | ||
else: self.send_error(400, 'Wrong content type') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
from http.server import HTTPServer | ||
from .handler import DataHandler | ||
|
||
class DataServer(HTTPServer): | ||
def __init__(self, queue, linked_list, host='localhost', port=8000): | ||
self._queue = queue() | ||
self._list = linked_list() | ||
super().__init__((host, port), | ||
lambda *args: DataHandler(self._queue, self._list, *args)) | ||
|
||
def run(self): | ||
self.serve_forever() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Refer to
Common Data Structure Operations
table here: https://www.bigocheatsheet.com/It is common that
insert
operation works for constant time. Your solution is O(n).Please, reconsider implementation and improve working time of
insert
method.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, but no. Insertion in single linked list is O(1) if we insert into the end of the list. But here the condition was to implement insertion before the successor, so we actually have two operations: searching for successor (which is O(n)) and then inserting (which is — after we have found a successor — is actually O(1)).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Dear @eoneoff , according to the table I mentioned earlier, insertion in singly-linked list is O(1) for both
average
andworst
cases. The problem here is thatsuccessor
has the same data type asvalue
, but it might be of typeNode
. Anyway it is up to you whether improve the working time or not, there is no specific requirement to fit O(1)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, but that makes on sense. To get the exact Note type object before which we want to insert a new Node with a value from the list, we still need to find it in the list (access complexity O(n)). So if we pass a Node as a successor we still first need to perform a search for this node with complexity O(n). And we do not have any other access to a random node in the list except by iterating the list one-by-one starting from the root node — than's the nature of the linked list.
Is is possible, of course, to separate these two operations and move a search to individual method, so the method for insertion would look like O(1). But the search method, which we will have to run before every insertion before successor will be still O(n), so general performance will be still O(n) too.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are right, but