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