@@ -29,12 +29,17 @@ def popped_indices(self):
2929 return nifty_collections .OrderedSet ()
3030
3131 def _get_sequence_index (self , index ):
32- current_base = 0
32+ if index < 0 :
33+ index += len (self )
34+ if not (0 <= index < self .length ):
35+ raise ValueError
36+ current_base = - 1 # Starting at -1 rather than 0 to ensure at least one
37+ # loop run
3338 current_goal = index
3439 while current_base != current_goal :
3540 n_popped_items_in_range = (
3641 bisect .bisect (self .popped_indices , current_goal ) -
37- len ( bisect .bisect_left (self .popped_indices , current_base ) ))
42+ bisect .bisect (self .popped_indices , current_base ))
3843 current_base , current_goal = (current_goal , current_goal +
3944 n_popped_items_in_range )
4045 assert current_goal not in self .popped_indices
@@ -61,16 +66,27 @@ def __iter__(self):
6166 # raise TypeError("Can't add stuff to a `%s`" % type(self).__name__)
6267 # extend = insert = append = _nopity_nope_nope
6368
64- clear = lambda self : self .popped_indices .__ior__ (range (len (self .sequence )))
69+ def clear (self ):
70+ self .popped_indices |= range (len (self .sequence ))
71+ self .popped_indices .sort ()
72+
6573 copy = lambda self : type (self )(self .sequence ,
6674 popped_indices = self .popped_indices )
67- __len__ = lambda self : len (self .sequence ) - len (self .popped_indices )
75+ length = property (
76+ lambda self : len (self .sequence ) - len (self .popped_indices ))
77+ __repr__ = lambda self : '%s(%s, popped_indices=%s)' % (
78+ type (self ).__name__ , self .sequence , self .popped_indices
79+ )
6880
6981 # These are the money methods right here:
7082 def pop (self , i ):
7183 sequence_index = self ._get_sequence_index (i )
72- self .popped_indices .add (sequence_index )
73- return self .sequence [sequence_index ]
84+ try :
85+ return self .sequence [sequence_index ]
86+ finally :
87+ self .popped_indices .add (sequence_index )
88+ self .popped_indices .sort ()
89+
7490 remove = lambda self , item : \
7591 self .popped_indices .add (self .sequence .index (item ))
7692
0 commit comments