Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Last active March 5, 2023 12:46
Show Gist options
  • 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
{
"cells": [
{
"cell_type": "markdown",
"id": "4613cc60-7366-4de3-a9a6-b8d20cc3eb05",
"metadata": {},
"source": [
"> - Iterable is an object, that one can iterate over. \n",
"It generates an Iterator when passed to iter() method.\n",
">\n",
"> - An iterator is an object, which is used to iterate over an iterable object \n",
"using the __next__() method. \n",
"Iterators have the __next__() method, \n",
"which returns the next item of the object.\n",
"https://www.geeksforgeeks.org/python-difference-iterable-iterator/\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "d83f2588-0404-4694-a8d5-2770854b1482",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"CircularList([1, 2, 'a'])"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from collections.abc import Iterable\n",
"class CircularList(Iterable):\n",
" \"\"\"\n",
" circular list with head\n",
" >>> cl = CircularList(['a'])\n",
" >>> isinstance(cl, Iterable)\n",
" True\n",
" \"\"\"\n",
" def __init__(self, it: Iterable = []):\n",
" self._l = []\n",
" for i in it:\n",
" self._l.append(i)\n",
" self._head: int = 0\n",
" \n",
" def __repr__(self):\n",
" return self.__class__.__name__ + '(' + repr(self._l) + ')'\n",
" \n",
" def __len__(self):\n",
" \"\"\"\n",
" >>> cl = CircularList(['a', 'b'])\n",
" >>> len(cl)\n",
" 2\n",
" \"\"\"\n",
" return len(self._l)\n",
" \n",
" def __iter__(self):\n",
" return iter(self._l)\n",
" \n",
" def __getitem__(self, idx:int):\n",
" \"\"\"\n",
" subscritable\n",
" \n",
" >>> cl = CircularList(['a'])\n",
" >>> cl[0]\n",
" 'a'\n",
" \"\"\"\n",
" return self._l[idx]\n",
" \n",
" # # not chage value\n",
" # def __setitem__(self, idx, v):\n",
" # \"\"\"\n",
" # support item assignment\n",
" # \"\"\"\n",
" # self._l[idx] = v\n",
" \n",
" @property\n",
" def head(self) -> int:\n",
" \"\"\"\n",
" >>> cl = CircularList(['a'])\n",
" >>> cl.head\n",
" 0\n",
" \"\"\"\n",
" return self._head\n",
" \n",
" def circ_iterator(self, step=1):\n",
" \"\"\"\n",
" \n",
" >>> cl = CircularList(['a', 'b'])\n",
" >>> ci = cl.circ_iterator()\n",
" >>> next(ci)\n",
" 'a'\n",
" >>> next(ci)\n",
" 'b'\n",
" >>> next(ci)\n",
" 'a'\n",
" \"\"\"\n",
" self.reset_head(0)\n",
" while self:\n",
" try:\n",
" yield self._l[self._head]\n",
" self._head += step\n",
" if self._head >= self.__len__():\n",
" self._head = 0\n",
" except StopIteration:\n",
" break\n",
" \n",
" def reset_head(self, h=-1):\n",
" \"\"\"\n",
" take head wanting - step\n",
" \n",
" # reset\n",
" >>> cl = CircularList(['a', 'b', 'c'])\n",
" >>> ci = cl.circ_iterator()\n",
" >>> next(ci)\n",
" 'a'\n",
" >>> next(ci)\n",
" 'b'\n",
" >>> cl.reset_head()\n",
" -1\n",
" >>> next(ci)\n",
" 'a'\n",
" \"\"\"\n",
" self._head = h\n",
" return self._head\n",
" \n",
" def append(self, x):\n",
" self._l.append(x)\n",
" return self._l\n",
" \n",
" @staticmethod\n",
" def doctest():\n",
" import doctest\n",
" doctest.testmod()\n",
"\n",
"CircularList.doctest()\n",
"l = CircularList([1,2,'a'])\n",
"l"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "0aa72995-89f4-4449-b1ad-327aa1efef99",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"l[l.head]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "92b35132-cf3c-4a62-b40e-1a708f91e048",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
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