I having a list of tuple as describes below (This tuple is sorted in decreasing order of the second value):
from string import ascii_letters
myTup = zip (ascii_letters, range(10)[::-1])
threshold = 5.5
>>> myTup
[('a', 9), ('b', 8), ('c', 7), ('d', 6), ('e', 5), ('f', 4), ('g', 3), ('h', 2), \
('i', 1), ('j', 0)]
Given a threshold, what is the best possible way to discard all tuples having the second value less than this threshold.
I am having more than 5 million tuples and thus don’t want to perform comparison tuple by tuple basis and consequently delete or add to another list of tuples.
Since the tuples are sorted, you can simply search for the first tuple with a value lower than the threshold, and then delete the remaining values using slice notation:
As Vaughn Cato points out, a binary search would speed things up even more.
bisect.bisectwould be useful, except that it won’t work with your current data structure unless you create a separate key sequence, as documented here. But that violates your prohibition on creating new lists.Still, you could use the source code as the basis for your own binary search. Or, you could change your data structure:
The disadvantage here is that the deletion may occur in linear time, since Python will have to shift the entire block of memory back… unless Python is smart about deleting slices that start from
0. (Anyone know?)Finally, if you’re really willing to change your data structure, you could do this:
(Note that Python 3 will complain about the
Nonecomparison, so you could use something like(-threshold, chr(0))instead.)My suspicion is that the linear time search I suggested at the beginning is acceptable in most circumstances.