Nas25 Nas25 - 11 days ago 5
Python Question

How to print matched item in range only once during a Python loop iteration

I am looking to search through my array [1,2,3,4,5] representing seconds and check whether my time variable 't' (intially 0) matches a range item, at which point I want to print that time 't' ONLY ONCE.

The loop will be read again but this time NOT print out anything unless another match is found - ie. t is now 2 seconds so when t = 2 then print 't' ONCE.

How can I achieve this in Python? This is what I currently have:

t = 0
dt = 0.05

a = np.arange(1,5,1)

while t < 10:

for x in range(a.size):
if int(t) == a[x,0]:
print "TIME IS NOW >>>>>>>", int(t)

t = t+dt


This is working except it is printing the previously matched number again and again until a new matched number is found:

TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>1
TIME IS NOW >>>>>>>2
TIME IS NOW >>>>>>>2


and so on.....

I want a RESULT of:

TIME IS NOW >>>>>>>1
-
-(looping but no print out)
TIME IS NOW >>>>>>>2
-
and so on...

Answer

Many thanks for the answers ,especially 'Copperfield' - your epsilon boundary check lead me to find out more about the issue of floating point numbers and although your solution didn't work for me directly I found a command using Numpy (since my array was a Numpy array) - the 'isclose' command. This seems to do what your solution does and checks the list items against a comparison using a tolerance.

The correct solution for my issue was:

if np.isclose(insRate, t, atol=0.0001).any():
    print "TIME IS NOW >>>>>>>", t

Thanks again everyone!