source: utilitiespy/tudelft/utilities/immutablelist/Range.py@ 958

Last change on this file since 958 was 662, checked in by wouter, 12 months ago

fixed code error (found by test)

File size: 2.0 KB
RevLine 
[222]1from decimal import Decimal, ROUND_FLOOR
[243]2from typing import List
[222]3
4from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
5
6
7class Range(AbstractImmutableList[Decimal]):
8 '''
9 Range is an immutable list of numbers from low to high with given step size.
10 This class is compatible with pyson.
11 '''
12 def __init__(self, low:Decimal, high: Decimal, step:Decimal):
[243]13 '''
14 @param low the first element in the range
15 @param high the maximum value of the range. The last item
16 in the range may be below or equal to this.
17 @param step this value is added to low repeatedly to give all elements
18 '''
19 assert isinstance(low, Decimal) and isinstance(high, Decimal) \
20 and isinstance(step, Decimal)
[222]21 self._low=low
22 self._high=high
23 self._step=step
24
[243]25 def getLow(self)->Decimal:
[222]26 return self._low
27
[243]28 def getHigh(self)->Decimal:
[222]29 return self._high
30
[243]31 def getStep(self)->Decimal:
[222]32 return self._step
33
[243]34 def get(self, index:int)-> Decimal:
[222]35 return self._low+ self._step * index
36
[243]37 def size(self) -> int:
[222]38 if self._low > self._high:
[243]39 return 0
40 return 1 + \
41 int( (( self._high - self._low )/self._step) .quantize(Decimal('1'), rounding=ROUND_FLOOR) )
[661]42
43 def contains(self, value:Decimal) -> bool:
44 '''
45 @param value value to look for
46 @return Returns true iff this contains the specified value.
47 '''
[662]48 return value>=self._low and value<= self._high and (value-self._low) % self._step == 0
[661]49
50
[222]51 def __eq__(self, other)->bool:
52 return isinstance(other, self.__class__) and \
53 self._low == other._low and \
54 self._high == other._high and\
55 self._step == other._step
56
57 def __repr__(self):
58 return "Range["+str(self._low)+","+str(self._high)+","+str(self._step)+"]"
59
60 def __hash__(self):
[243]61 return hash((self._low, self._high, self._step))
[222]62
Note: See TracBrowser for help on using the repository browser.