![]() ![]() ![]() It will have the desired big O performance characteristics however.Įxample of usage: > l = LinkedList() It won't be as space or time efficient as lisp cons cells, as python classes are obviously a bit more heavyweight (You could improve things slightly with " _slots_ = '_head','_tail'" to reduce memory usage). It should have O(1) prepend, doesn't copy data unless it needs to and can be used pretty interchangably with tuples. supports indexing, slicing, concatenation with arbitrary sequences etc). Here's a slightly more complex version of a linked list class, with a similar interface to python's sequence types (ie. Out = 'LinkedList [\n' str(current.value) '\n' class Node:ĭef _init_(self, value = None, next = None): It is a simple LinkedList class based on the straightforward C design and Chapter 17: Linked lists, as recommended by Thomas Watnedal. Here is a more standard design: L = LinkedList() The accepted answer is rather complicated. class Node:ĭef _init_(self, cargo=None, next=None): the empty list, represented by None, orĪ node that contains a cargo object and a reference to a linked list. ![]() Thomas Watnedal suggested a good educational resource How to Think Like a Computer Scientist, Chapter 17: Linked lists: I've never used a singly linked list in Python for any problem except educational. Length = lambda lst, count=0: length(cdr(lst), count 1) if lst else countĭisplay = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")Īlthough doubly linked lists are famously used in Raymond Hettinger's ordered set recipe, singly linked lists have no practical value in Python. Nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst) Mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None) Löwis's representation: cons = lambda el, lst: (el, lst) Here is some list functions based on Martin v. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |