[python-nl] fast & simple ?

Floris van Manen vm at klankschap.nl
Wed Mar 4 23:47:05 CET 2009


L.S. !

Just in case someone is in the mood to find a faster & simpler way to  
this piece of code ...
Thanks !
.Floris


import random

def LinearInter(f, a, b):
	return a + (b-a) * f

def FindSegment(r, A=[], FACT=0, DATA=1 ):
	if r <= A[0][FACT]:
		return A[0][DATA]
	elif r >= A[-1][FACT]:
		return A[-1][DATA]
	else:
		l = 0
		h = len(A)-1
		while (h-l) > 1:
			p = l + (h-l) / 2
			if r >= A[p][FACT]:
				l = p
			else:
				h = p
		if l == h:
			return A[l][DATA]
		return LinearInter( (r - A[l][FACT]) / (A[h][FACT] - A[l][FACT]),  
A[l][DATA], A[h][DATA] )

if __name__ == '__main__':
	L1 = [ (0.0,  10), (0.5,  20), (0.75, 30), (0.8,  40), (1.0,  50) ]
	L2 = [ (0.1,  50), (0.5,  30), (0.75, 10), (0.8,  40), (0.9,  70) ]

	for i in range(101):
		r = i / 100.0
		print i, FindSegment(r, L1), FindSegment(r, L2),  
FindSegment(random.random(), L2)




More information about the Python-nl mailing list