You can also take a look at llist python package, which provides some useful features that deque does not. There are not only doubly linked lists, but also single linked lists data structure in that package. IMHO, one of the biggest advantages of this package is the ability to store a reference to the llist elements.
You can also take a look at llist python package, which provides some useful features that deque does not. There are not only doubly linked lists, but also single linked lists data structure in that package. IMHO, one of the biggest advantages of this package is the ability to store a reference to the llist elements.
It appears that collections.deque is a doubly-linked-list library in Python. According to the documentation, it should have approximately O(1) cost when appending or popping from the head or the tail, as well as O(n) for regular inserts (which matches what we'd expect from a linked list).
API: http://docs.python.org/2/library/collections.html#collections.deque
Source: https://stackoverflow.com/a/282238/2441252
For the most part it looks good, I haven't tested performance, but nothing stands out as bad. You should probably rewrite remove, so that it takes an index rather than a value. Imagine
list = LinkedList()
list.insert(2)
list.insert(2)
list.remove(2)
Your current code works great as long as there aren't duplicate values, but once there are everything gets kind of messed up.
With regards to pythonicness, the only comment I have is that if(x): is harder to type and harder to parse than if x:.
You should not name variables and parameters the same as Python built-in names, such as next (see this).
The reason is because you are redefining what Python already defined. Now anyone, including you, relying on that Python builtin by importing your code might see unexpected side effects. See this simple illustration; once you modify Python builtin list to be an instance of list, one cannot call list() again:
>>> x = list()
>>> x
[]
>>> list = [5]
>>> y = list()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not callable
Summary
I won't dwell on what has already been cited by users toolic and J_H, so I just have a few comments:
Type Hinting
I would suggest that you include type hinting, especially if your functions do not contain docstrings that describe the type of arguments being passed to functions (J_H has suggested this, so pardon if this is too repetitive).
Be More Tolerant of Errors in User Input
If the user does not enter a valid integer in function run_and_add, you essentially quit. You should instead put out the prompt again and give the user as many chances needed to enter valid input. The user can always terminate by entering Ctrl-C if they get stuck.
Strive for Encapsulation and Reusability
I can't stress too strongly that your code is crying out for you to create a LinkedList abstract data type that abstracts the notion of a linked list while encapsulating the actual implementation. To that end, I would use attribute names that begin with '_' where appropriate to suggest that they are "private" and not to be either updated nor depended on existing in the future (such as the next instance attribute of the ListNode class.
The following classes are just one possibility. Note:
- There is no
printmethod implemented since printing the entire list is trivial given that the class implements the iterator protocol. Besides, what if you wanted to print to a file? Then aprintmethod would require one or more additional arguments. - The client never explicitly creates
ListNodeinstances. - The linked list keeps explicit track of the final (last) node in the list to provide efficient appending of a node or an entire linked list to the end.
I can envision your using this as a starting point and potentially adding other methods (for example, __eq__ methods to compare nodes and linked lists).
"""A module for creating and manipulating linked lists."""
from abc import ABC, abstractmethod
from typing import TypeVar, Any
LinkedListInstance = TypeVar('LinedListInstance', bound='LinkedList')
class NodeType(ABC):
@property
@abstractmethod
def val(self):
pass
@val.setter
@abstractmethod
def val(self, val):
pass
class LinkedList:
class _ListNode(NodeType):
"""Initialize a new node with some value, val."""
def __init__(self, val):
self._val = val
self._next = None
@property
def val(self):
return self._val
@val.setter
def val(self, val):
self._val = val
def __repr__(self):
return f'_ListNode({repr(self._val)})'
def __str__(self):
return str(self._val)
def __init__(self):
"""Create a new, empty linked list."""
self._head = None
self._tail = None
def append_node(self, val: Any) -> LinkedListInstance:
"""Append a new node to the list initialized with val."""
new_node = LinkedList._ListNode(val)
if self._head is None:
self._head = new_node
else:
self._tail._next = new_node
self._tail = new_node
return self
def insert_node(self, at_node: NodeType, val: Any) -> LinkedListInstance:
"""Create and insert a new node after the specified at_node node initialized
with val."""
if at_node is self._tail: # special case
return self.append_node(val)
node_to_insert = LinkedList._ListNode(val)
node_to_insert._next = at_node._next
at_node._next = node_to_insert
return self
def append_list(self, linked_list: LinkedListInstance) -> LinkedListInstance:
"""Append a linked list to the current list."""
if self._head is None:
self._head = linked_list._head
else:
self._tail._next = self._head
self._tail = linked_list._tail
return self
def __iter__(self) -> NodeType:
"""Iterate the list."""
current = self._head
while current is not None:
yield current
current = current._next
if __name__ == '__main__':
def insert_node_at_position(linked_list: LinkedList, position: int) -> None:
for counter, current_node in enumerate(linked_list, start=1):
print(f"Node at position {counter}: {current_node}")
if counter == position:
while True:
try:
number = int(input("Please insert an Integer: "))
except ValueError:
print("Not an Integer")
else:
break
linked_list.insert_node(current_node, number)
print("Node added at position:", position)
print("Updated linked list:")
for node in linked_list:
print(node)
linked_list = LinkedList().append_node(1).append_node(2).append_node(3)
insert_node_at_position(linked_list, 2)
names
class ListNode:
This is a perfectly fine identifier, as-is.
There's no adjacent code that uses other node types.
Consider shortening to just Node.
design of Public API
OO
def print_linked_list(head):
...
def add_node(prev_node, node_to_add):
...
These are somewhat unexpected signatures,
the sort of thing I might expect in Fortran code.
ListNode turned out to be just a very brief
@dataclass,
with no OO
aspect to it.
Given a ListNode, we find no methods to call on it for list operations.
This works, but makes it a little harder for developers
and maintenance engineers to discover your API.
For example if I hit a breakpoint() I cannot p dir(node)
to find plausible things I might do with a node -- I instead
have to scour the codebase for such operations.
Also, your signatures lack ListNode type annotations,
so I can't just grep for that or use type-aware IDE features
to narrow my search.
I propose some more natural implementations.
def print_linked_list(self):
head = self
while head:
print(head.val)
head = head.next
def add_node(self, node_to_add):
assert node_to_add.next is None
node_to_add.next = self.next
self.next = node_to_add
Consider renaming these to simply .print() and .insert().
interactive input vs parameter
(I am paraphrasing, renaming the vague number to new_val.)
def run_and_add(head, position):
...
new_val = int(input("Please insert an Integer: "))
Prefer to place calls of input() further up in the call stack,
such as within def main():, and pass in such a value as a parameter:
def run_and_add(head, position, new_val):
main guard
On which topic, you don't have a main() function,
and you really need one.
Why?
So you or some maintenance engineer can safely import linkedlist
when exercising your functions in a
test suite.
Also, it's convenient to ensure that local variables like first
(which are not part of your exported Public API)
will disappear when they go out of scope.
That way such identifiers won't pollute the module namespace.
def main():
first = ListNode(1)
first.next = ListNode(2)
first.next.next = ListNode(3)
run_and_add(first, 2)
if __name__ == '__main__':
main()
single responsibility
run_and_add() is an awkward identifier, suggesting that instead of
one
we're doing two things.
Also I find "run" less than clear.
Consider making caller responsible for passing in an already-created node,
and then this could be a simple insert_at_position(head, position, new_node) function.
For some needs, a deque may also be useful. You can add and remove items on both ends of a deque at O(1) cost.
from collections import deque
d = deque([1,2,3,4])
print d
for x in d:
print x
print d.pop(), d
Here is some list functions based on Martin v. Löwis's representation:
cons = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")
where w = sys.stdout.write
Although doubly linked lists are famously used in Raymond Hettinger's ordered set recipe, singly linked lists have no practical value in Python.
I've never used a singly linked list in Python for any problem except educational.
Thomas Watnedal suggested a good educational resource How to Think Like a Computer Scientist, Chapter 17: Linked lists:
A linked list is either:
- the empty list, represented by None, or
a node that contains a cargo object and a reference to a linked list.
class Node: def __init__(self, cargo=None, next=None): self.car = cargo self.cdr = next def __str__(self): return str(self.car) def display(lst): if lst: w("%s " % lst) display(lst.cdr) else: w("nil\n")