source: utilitiespy/tudelft/utilities/immutablelist/ListWithRemove.py@ 1323

Last change on this file since 1323 was 1002, checked in by wouter, 4 months ago

#340 added tests, found issue with translation, fixed, all tests OK, redeployed 1.0.7.

File size: 1.7 KB
Line 
1from __future__ import annotations
2from typing import TypeVar, Generic, List
3from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
4from tudelft.utilities.immutablelist.ImmutableList import ImmutableList
5from typing import Set
6
7E = TypeVar('E')
8
9class ListWithRemove(Generic[E], AbstractImmutableList[E]):
10 '''
11 Creates new list with some elements removed from the list. Immutable
12 @param list an ImmutableList
13 @param removed the removed items. Set to empty set initially.
14 '''
15
16 def __init__(self, list: ImmutableList[E], removed: Set[int]):
17 self._list = list
18 self._removedIndices=sorted(frozenset(removed))
19
20
21 #Override
22 def get(self , index:int) ->E :
23 return self._list.get(self._realIndex(index))
24
25 def _realIndex(self, index:int) -> int:
26 '''
27 @param index
28 @return the real index of an item in the original list. This can be
29 larger than given index because {@link #remvedIndices} are
30 invisible. This operation can become expensive if many items have
31 been removed
32 '''
33 realIndex:int = index;
34
35 # invariant: realIndex has correct value if only removedIndices up to
36 # current iteration were in the list.
37 for removed in self._removedIndices:
38 if removed > realIndex:
39 break
40 realIndex += 1
41
42 return realIndex;
43
44
45 #Override
46 def size(self) ->int:
47 return self._list.size() - len(self._removedIndices)
48
49 def remove(self, index:int) -> ListWithRemove[E]:
50 '''
51 Remove item at index n
52
53 @param index index of the element to return
54 @return the element at the specified position in this list before it was
55 removed.
56 '''
57 removed:Set[int] = set(self._removedIndices)
58 removed.add(self._realIndex(index));
59 return ListWithRemove(self._list, removed);
Note: See TracBrowser for help on using the repository browser.