From 162cceaa57dc1213d1afab8832f84070410ad174 Mon Sep 17 00:00:00 2001 From: Dominik Roth Date: Fri, 18 Nov 2022 15:30:19 +0100 Subject: [PATCH] initial commit --- .gitignore | 1 + README.md | 9 +++++++ lazyList.py | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 lazyList.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/README.md b/README.md new file mode 100644 index 0000000..64bdc7a --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +Is it a list? Is it a generator? No its a +# LazyList + +Have you ever found yourself in a situation, where you used a generator, but then realized, that you sometimes need an element from further in the future? Or specific past element? This very specific problem is no more, thank to LazyList! (Wow!) + +## What does it do? +It's a list, that gets initialied using an iterable. The list uses the iterable to generate when new elements are accessed. + +TODO: Bla diff --git a/lazyList.py b/lazyList.py new file mode 100644 index 0000000..079189f --- /dev/null +++ b/lazyList.py @@ -0,0 +1,76 @@ +from math import inf + +class LazyList(list): + def __init__(self, iterable): + self._iter = iterable + self._length = inf + self._n = 0 + + def __setitem__(self, index, item): + self._requireLen(index) + super().__setitem__(index, item) + + def __len__(self): + return self._length + + def __repr__(self): + if super().__len__() == 0: + return '[...]' + l = [] + for i in range(super().__len__()): + l.append(str(self[i])) + if self._length != inf: + return '[' + ', '.join(l) + ']' + else: + return '[' + ', '.join(l) + ', ...]' + + def __str__(self): + return repr(self) + + def _requireLen(self, length): + if length==-1: + num = inf + else: + num = length - super().__len__() + 1 + if num > 0: + i = 0 + while i < num: + try: + super().append(self._iter.__next__()) + except StopIteration as e: + self._length = super().__len__() + if length!=-1: + raise e + return + i+=1 + + def __iter__(self): + self._n = 0 + return self + + def __next__(self): + ret = self[self._n] + self._n += 1 + return ret + + def peak(self, offset=0): + return self[self._n - 1 + offset] + + def iterIndex(self): + return self._n - 1 + + def __getitem__(self, index): + self._requireLen(index) + return super().__getitem__(index) + + def insert(self, index, item): + self._requireLen(index-1) + super().insert(index, item) + + def append(self, item): + self._requireLen(-1) + super().append(item) + + def extend(self, other): + self._requireLen(-1) + super().extend(other)