Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active March 19, 2021 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/e3f965aa31101f28ad955086d0f89354 to your computer and use it in GitHub Desktop.
Save JoshCheek/e3f965aa31101f28ad955086d0f89354 to your computer and use it in GitHub Desktop.
linked list in Python
import functools
class LList:
@classmethod
def fromArray(cls, array):
return functools.reduce(lambda ll, val: ll.append(val), array, cls())
def __init__(self): self.isEmpty = True
def append(self, val): return LNode(val, self)
def __iter__(self): return self
def next(self): raise StopIteration
def __len__(self): return 0
def __repr__(self): return 'LList()'
def __str__(self, pre='(', delim=''): return pre + ')'
class LNode:
def __init__(self, val, rest):
self.val = val
self.rest = rest
def append(self, val):
return LNode(self.val, self.rest.append(val))
def __iter__(ll):
yield ll.val
for val in ll.rest: yield val
# is there not a way I can just pass execution to `ll.next`?
# I think this "for val in" thing means we've got a stack of iterators
# each yielding their value up through the stack to the top one which
# finally yields it to the the thing receiving it.
# In Ruby, you would do it like this:
# def each(&block)
# block.call val
# rest.each &block
# end
# where `block.call` is equivalent to `yield`, so you can pass the thing
# that is being yielded to.
def __len__(self):
return 1 + len(self.rest)
def __str__(self, pre='(', delim=''):
return pre + delim + str(self.val) + self.rest.__str__('', '->')
def __repr__(self):
return 'LNode({0!r}, {1!r})'.format(self.val, self.rest)
def show(ll):
print('ll = {0!r}'.format(ll))
print('len(ll) # => {0}'.format(len(ll)))
print('print(ll) # => {0}'.format(ll))
print('')
show(LList.fromArray([]))
show(LList.fromArray([11,22,33]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment