1
0
mirror of https://github.com/exaloop/codon.git synced 2025-06-03 15:03:52 +08:00
codon/stdlib/sortedlist.codon
Ibrahim Numanagić 5de233a64e
Dynamic Polymorphism (#58)
* Use Static[] for static inheritance

* Support .seq extension

* Fix #36

* Polymorphic typechecking; vtables [wip]

* v-table dispatch [wip]

* vtable routing [wip; bug]

* vtable routing [MVP]

* Fix texts

* Add union type support

* Update FAQs

* Clarify

* Add BSL license

* Add makeUnion

* Add IR UnionType

* Update union representation in LLVM

* Update README

* Update README.md

* Update README

* Update README.md

* Add benchmarks

* Add more benchmarks and README

* Add primes benchmark

* Update benchmarks

* Fix cpp

* Clean up list

* Update faq.md

* Add binary trees benchmark

* Add fannkuch benchmark

* Fix paths

* Add PyPy

* Abort on fail

* More benchmarks

* Add cpp word_count

* Update set_partition cpp

* Add nbody cpp

* Add TAQ cpp; fix word_count timing

* Update CODEOWNERS

* Update README

* Update README.md

* Update CODEOWNERS

* Fix bench script

* Update binary_trees.cpp

* Update taq.cpp

* Fix primes benchmark

* Add mandelbrot benchmark

* Fix OpenMP init

* Add Module::unsafeGetUnionType

* UnionType [wip] [skip ci]

* Integrate IR unions and Union

* UnionType refactor [skip ci]

* Update README.md

* Update docs

* UnionType [wip] [skip ci]

* UnionType and automatic unions

* Add Slack

* Update faq.md

* Refactor types

* New error reporting [wip]

* New error reporting [wip]

* peglib updates [wip] [skip_ci]

* Fix parsing issues

* Fix parsing issues

* Fix error reporting issues

* Make sure random module matches Python

* Update releases.md

* Fix tests

* Fix #59

* Fix #57

* Fix #50

* Fix #49

* Fix #26; Fix #51; Fix #47; Fix #49

* Fix collection extension methods

* Fix #62

* Handle *args/**kwargs with Callable[]; Fix #43

* Fix #43

* Fix Ptr.__sub__; Fix polymorphism issues

* Add typeinfo

* clang-format

* Upgrade fmtlib to v9; Use CPM for fmtlib; format spec support; __format__ support

* Use CPM for semver and toml++

* Remove extension check

* Revamp str methods

* Update str.zfill

* Fix thunk crashes [wip] [skip_ci]

* Fix str.__reversed__

* Fix count_with_max

* Fix vtable memory allocation issues

* Add poly AST tests

* Use PDQsort when stability does not matter

* Fix dotted imports; Fix  issues

* Fix kwargs passing to Python

* Fix #61

* Fix #37

* Add isinstance support for unions; Union methods return Union type if different

* clang-format

* Nicely format error tracebacks

* Fix build issues; clang-format

* Fix OpenMP init

* Fix OpenMP init

* Update README.md

* Fix tests

* Update license [skip ci]

* Update license [ci skip]

* Add copyright header to all source files

* Fix super(); Fix error recovery in ClassStmt

* Clean up whitespace [ci skip]

* Use Python 3.9 on CI

* Print info in random test

* Fix single unions

* Update random_test.codon

* Fix polymorhic thunk instantiation

* Fix random test

* Add operator.attrgetter and operator.methodcaller

* Add code documentation

* Update documentation

* Update README.md

* Fix tests

* Fix random init

Co-authored-by: A. R. Shajii <ars@ars.me>
2022-12-04 19:45:21 -05:00

130 lines
3.7 KiB
Python

# Copyright (C) 2022 Exaloop Inc. <https://exaloop.io>
from bisect import bisect_right, bisect_left, insort
from collections import deque
DEFAULT_LOAD_FACTOR = 1000
class SortedList:
_len: int
_load: int
_lists: List[List[T]]
_maxes: List[T]
_offset: int
T: type
def __init__(self):
self._len = 0
self._load = DEFAULT_LOAD_FACTOR
self._lists = []
self._maxes = []
self._offset = 0
def clear(self):
"""
Remove all values from sorted list.
Runtime complexity: `O(n)`
"""
self._len = 0
self._lists.clear()
self._maxes.clear()
self._offset = 0
@property
def left(self) -> T:
if not self._lists:
raise IndexError("list index out of range")
return self._lists[0][0]
def add(self, value: T):
"""
Add `value` to sorted list.
Runtime complexity: `O(log(n))` -- approximate.
>>> sl = SortedList()
>>> sl.add(3)
>>> sl.add(1)
>>> sl.add(2)
>>> sl
SortedList([1, 2, 3])
:param value: value to add to sorted list
"""
if self._maxes:
pos = bisect_right(self._maxes, value)
if pos == len(self._maxes):
pos -= 1
self._lists[pos].append(value)
self._maxes[pos] = value
else:
insort(self._lists[pos], value)
self._expand(pos)
else:
self._lists.append([value])
self._maxes.append(value)
self._len += 1
def _expand(self, pos: int):
"""
Split sublists with length greater than double the load-factor.
Updates the index when the sublist length is less than double the load
level. This requires incrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
"""
if len(self._lists[pos]) > (self._load << 1):
_maxes = self._maxes
_lists_pos = self._lists[pos]
half = _lists_pos[self._load :]
del _lists_pos[self._load :]
_maxes[pos] = _lists_pos[-1]
self._lists.insert(pos + 1, half)
_maxes.insert(pos + 1, half[-1])
def _delete(self, pos: int, idx: int):
"""
Delete value at the given `(pos, idx)`.
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the
leaf node to the root. For an example traversal see
``SortedList._loc``.
:param int pos: lists index
:param int idx: sublist index
"""
_lists_pos = self._lists[pos]
del _lists_pos[idx]
self._len -= 1
len_lists_pos = len(_lists_pos)
if len_lists_pos > (self._load >> 1):
self._maxes[pos] = _lists_pos[-1]
elif len(self._lists) > 1:
if not pos:
pos += 1
prev = pos - 1
self._lists[prev].extend(self._lists[pos])
self._maxes[prev] = self._lists[prev][-1]
del self._lists[pos]
del self._maxes[pos]
self._expand(prev)
elif len_lists_pos:
self._maxes[pos] = _lists_pos[-1]
else:
del self._lists[pos]
del self._maxes[pos]
def __iter__(self) -> Generator[T]:
for l in self._lists:
yield from l
def __len__(self) -> int:
return self._len
def __bool__(self) -> bool:
return self._len > 0