[Tutor] finding numbers in range of of numbers

ALAN GAULD alan.gauld at btinternet.com
Tue Oct 21 16:42:38 CEST 2008



a = [['xa','1511255', '1511279'],['xb','7516599','7516623'],['xc','98356290','98356266']]

b = [['G1','1511200','1511325'],['G2','7516500','7516625'],['G3','98356335','98356126']]

>>> for item1 in a:
...     i1st = int(item1[1])
...     i1en = int(item1[2])
...     for item2 in b:
...             i21 = int(item2[1])
...             i22 = int(item2[2])
...             if i1st and i1en in xrange(i21,i22):
...                     print "\t".join(item1)+'\t'+"\t".join(item2)
...             if i1st and i1en in xrange(i22,i21):
...                     print "\t".join(item1)+'\t'+"\t".join(item2)


I would rewrite the 4 lines above to remove the 'in' test - which is basically
iterating over the range.

if i1st:         # is this really the logic you want? it seems slightly suspicious to me
   if i21 < i1en < i22:
     # i21 is within the range.

That should save one iteration of the range for each inner loop. 
(One iteration is always of an empty list depending on which of i21,i22 is greater)

> Issue 1:  
> a. Range of numbers is too high and xrange is also too slow.
>    I used xrange instead of range - a slow process


My solution removes the use of xrange.

> Issue 2: 
> Is this is a correct way to tackle this kind of problem. 

If it works then in a sense its correct. But I think checking the range 
boundaries is easier and should be faster

> Issue 3: 
> I have 200K elements in a anb b lists. this code has been running for 
> last 18 hours and only 800 elements of 200K have been evaluated. 

Which is a repeat of issue 1... I don't know how much my proposed 
solution will make but it should be a bit faster.

Dunno if that will help,

Alan G


More information about the Tutor mailing list