1 |
|
---|
2 |
|
---|
3 | from collections.abc import Iterator
|
---|
4 | from itertools import tee
|
---|
5 | from typing import Tuple, TypeVar, Collection, Any, List
|
---|
6 |
|
---|
7 | def hasNext(it)->Tuple[bool, Iterator]:
|
---|
8 | '''
|
---|
9 | A support function to test hasNext for standard python iterators.
|
---|
10 | usage, assuming it is already created (eg it=iter([1,2,3]):
|
---|
11 | nx, it = hasNext(it)
|
---|
12 |
|
---|
13 | After the call, nx will be True iff it has a next value.
|
---|
14 | The new it will be in original state (we have to damage the original iterator)
|
---|
15 | '''
|
---|
16 |
|
---|
17 | it,it1=tee(it)
|
---|
18 | try:
|
---|
19 | next(it1)
|
---|
20 | return True, it
|
---|
21 | except:
|
---|
22 | return False, it
|
---|
23 |
|
---|
24 | T=TypeVar("T")
|
---|
25 | def removeFirst(lst:Collection[T], it: Any) -> bool:
|
---|
26 | '''
|
---|
27 | remove first occurence of it from lst
|
---|
28 | @param lst a list to remove items from
|
---|
29 | @param it an item to remove
|
---|
30 | @return True if lst was modified, else False
|
---|
31 |
|
---|
32 | '''
|
---|
33 | if not it in lst:
|
---|
34 | return False
|
---|
35 | lst.remove(it) # type: ignore
|
---|
36 | return True
|
---|
37 |
|
---|
38 |
|
---|
39 | def remove(lst:List[T], it: Any) -> bool:
|
---|
40 | '''
|
---|
41 | remove all occurences of it from lst
|
---|
42 | @param lst a list to remove items from
|
---|
43 | @param it an item to remove
|
---|
44 | @return True if lst was modified
|
---|
45 |
|
---|
46 | '''
|
---|
47 | n=lst.count(it)
|
---|
48 | for i in range(n):
|
---|
49 | lst.remove(it)
|
---|
50 | return n>0
|
---|
51 |
|
---|
52 | def removeAll(lst:List[T], toremove:Collection[Any]) -> bool:
|
---|
53 | '''
|
---|
54 | all items in toremove are removed from lst
|
---|
55 | @param lst a list to remove items from
|
---|
56 | @param toremove a list of items to remove
|
---|
57 | @return True if lst was modified
|
---|
58 | '''
|
---|
59 | return any([remove(lst,it) for it in toremove])
|
---|
60 |
|
---|