Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active March 5, 2023 12:46
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 Cartman0/bc820d27ea1bfac269542bae5e0e5ca9 to your computer and use it in GitHub Desktop.
Save Cartman0/bc820d27ea1bfac269542bae5e0e5ca9 to your computer and use it in GitHub Desktop.
python Circular List
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
from collections import deque
'''
This one is implemented in C code for CPython, and the collections python module just imports that name.
https://stackoverflow.com/questions/54526226/how-can-i-see-the-source-code-of-deque-module-from-pythons-collections-library
'''
class Deque_withHead(deque):
"""
add head
"""
def __init__(self, iterable=[], maxlen=None):
super().__init__(iterable=iterable, maxlen=maxlen)
self._head = 0
def rotate(self, n:int = 1):
super().rotate(n)
self._head += n
if self._head < 0:
self._head += len(self)
def reverse(self):
super().reverse()
self._head = len(self) - 1 - self._head
def head(self)->int:
return self._head
def reset_head(self):
pass
def insert(self, i, x):
super().insert(i, x)
if i <= self._head:
self._head += 1
def popleft(self):
super().popleft()
self._head -= 1
if self._head < 0:
self._head = 0
def pop(self):
super().pop()
if self._head > len(self) - 1:
self._head = len(self) - 1
def iteratornize(self):
"""
iteratornize_deque(('ABC', 'D', 'EF')) --> ABC D EF
"""
while self:
try:
yield self[0]
self.rotate(-1)
except StopIteration:
break
dh=Deque_withHead(['a', 'b', 'c'])
print(dh, dh[dh.head()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment