@@ -835,6 +835,78 @@ def __repr__(self):
835
835
return 'SequenceZip({})' .format (self .sequences )
836
836
837
837
838
+ class Repeater (object ):
839
+ """
840
+ Returns a virtual sequence with value repeated n times.
841
+ The sequence is never actually created in memory.
842
+
843
+ Parameters
844
+ ----------
845
+ value : any
846
+ Value to repeat.
847
+ n : int
848
+ Number of times to repeat value.
849
+
850
+ Notes
851
+ -----
852
+ This is very similar to itertools.repeat except this version returns a Sequence instead of an iterator,
853
+ meaning it has a length and can be indexed.
854
+
855
+ Examples
856
+ --------
857
+ >>> r = Repeater('a', 3)
858
+ >>> list(r)
859
+ ['a', 'a', 'a']
860
+ >>> r[0]
861
+ 'a'
862
+ >>> r[2]
863
+ 'a'
864
+ >>> r[3]
865
+ Traceback (most recent call last):
866
+ ...
867
+ IndexError: index out of range
868
+ >>> r[-1]
869
+ 'a'
870
+ >>> r[-3]
871
+ 'a'
872
+ >>> r[-4]
873
+ Traceback (most recent call last):
874
+ ...
875
+ IndexError: index out of range
876
+ >>> len(r)
877
+ 3
878
+ >>> list(r[1:])
879
+ ['a', 'a']
880
+ >>> list(r[:2])
881
+ ['a', 'a']
882
+ >>> list(r[10:])
883
+ []
884
+ """
885
+ def __init__ (self , value , n ):
886
+ self .value = value
887
+ self .n = n
888
+
889
+ def __len__ (self ):
890
+ return self .n
891
+
892
+ def __getitem__ (self , key ):
893
+ if isinstance (key , (int , np .integer )):
894
+ if key >= self .n or key < - self .n :
895
+ raise IndexError ('index out of range' )
896
+ return self .value
897
+ else :
898
+ assert isinstance (key , slice ), "key (%s) has invalid type (%s)" % (key , type (key ))
899
+ start , stop , step = key .indices (self .n )
900
+ # XXX: unsure // step is correct
901
+ return Repeater (self .value , (stop - start ) // step )
902
+
903
+ def __iter__ (self ):
904
+ return itertools .repeat (self .value , self .n )
905
+
906
+ def __repr__ (self ):
907
+ return 'Repeater({}, {})' .format (self .value , self .n )
908
+
909
+
838
910
# TODO: remove Product from larray_editor.utils (it is almost identical)
839
911
class Product (object ):
840
912
"""
0 commit comments