-1

So im trying to check if some lists are close enough to each other. But i dont know how to make it go through every single value before deciding if its close or not.

import math
A=[5.230001, 6.8300001, 10.000001,11.33]
B=[5.23, 7.83, 10.00, 11.31]

for i in range(len(A)):
    if math.isclose( A[i], B[i], abs_tol=0.01):
        print("close enough")
        break
    else:
        print("not close")

If supposed to get a "not close" output due to the last value but it already concludes that its close due to the earlier values? How am i supposed to do this? Ive tried setting the starting index to 0 and then trying to iterate from that but that just broke it even more and at this point im out of ideas

Aplet123
  • 33,825
  • 1
  • 29
  • 55
Notan
  • 3
  • 1

2 Answers2

1

Python has builtin functions for that:

if all(math.isclose(a, b, abs_tol=0.01) for a, b in zip(A, B)):
    print("close enough")
else:
    print("not close")

If you wanted the opposite (at least 1 instead of all) you can use any instead.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
0

The logic is backwards: you should break from the loop as soon as you find the first element that is not close to the other:

import math
A=[5.230001, 6.8300001, 10.000001,11.33]
B=[5.23, 7.83, 10.00, 11.31]

all_close = True
for i in range(len(A)):
    if math.isclose( A[i], B[i], abs_tol=0.01):
        print("close enough")
    else:
        print("not close")
        all_close = False
        break  # <--- HERE

print("Are they all close?", all_close)
ForceBru
  • 43,482
  • 10
  • 63
  • 98