Skip to content
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
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .stack import Stack
from .linked_list import LinkedList
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:

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.

Copy link
Author

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)).

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 and worst cases. The problem here is that successor has the same data type as value, but it might be of type Node. Anyway it is up to you whether improve the working time or not, there is no specific requirement to fit O(1)

Copy link
Author

@eoneoff eoneoff Oct 17, 2019

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.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, but

  1. insert and access are two different operations, and you can split your code into two operations
  2. having successor of type Node, you already have all the data to perform insert operation, no need to perform a search first

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 submissions/eoneoff/data-structures-http/data_structures/node.py
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 submissions/eoneoff/data-structures-http/data_structures/stack.py
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
35 changes: 35 additions & 0 deletions submissions/eoneoff/data-structures-http/main.py
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()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .server import DataServer
84 changes: 84 additions & 0 deletions submissions/eoneoff/data-structures-http/server/handler.py
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')
12 changes: 12 additions & 0 deletions submissions/eoneoff/data-structures-http/server/server.py
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()