source: utilitiespy/tudelft/utilities/tools/Iterator.py

Last change on this file was 1310, checked in by wouter, 2 weeks ago

#407 added removeAll and remove to iterator - python does not have this functionality

File size: 1.1 KB
Line 
1
2
3from collections.abc import Iterator
4from itertools import tee
5from typing import Tuple, TypeVar, Collection, Any, List
6
7def 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
24T=TypeVar("T")
25def remove(lst:List[T], it: Any) -> bool:
26 '''
27 remove all occurences 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
31
32 '''
33 n=lst.count(it)
34 for i in range(n):
35 lst.remove(it)
36 return n>0
37
38def removeAll(lst:List[T], toremove:Collection[Any]) -> bool:
39 '''
40 all items in toremove are removed from lst
41 @param lst a list to remove items from
42 @param toremove a list of items to remove
43 @return True if lst was modified
44 '''
45 return any([remove(lst,it) for it in toremove])
46
Note: See TracBrowser for help on using the repository browser.