Bird
0
0

You want to test if a list of floating numbers is approximately equal to expected values with a tolerance of 0.01. Which is the best way to write the assertion?

hard🚀 Application Q8 of 15
PyTest - Writing Assertions
You want to test if a list of floating numbers is approximately equal to expected values with a tolerance of 0.01. Which is the best way to write the assertion?
Aassert actual_list == pytest.approx(expected_list, abs=0.01)
Bassert actual_list == pytest.approx(expected_list, rel=0.01)
Cassert all(abs(a - e) < 0.01 for a, e in zip(actual_list, expected_list))
Dassert actual_list == expected_list
Step-by-Step Solution
Solution:
  1. Step 1: Understand absolute vs relative tolerance

    abs=0.01 sets an absolute tolerance, suitable for fixed margin comparisons.
  2. Step 2: Check options for list comparison

    pytest.approx supports list comparisons with abs parameter. assert actual_list == pytest.approx(expected_list, abs=0.01) uses this correctly. assert actual_list == pytest.approx(expected_list, rel=0.01) uses relative tolerance which may not fit fixed margin. assert all(abs(a - e) < 0.01 for a, e in zip(actual_list, expected_list)) is manual but less concise. assert actual_list == expected_list requires exact equality.
  3. Final Answer:

    assert actual_list == pytest.approx(expected_list, abs=0.01) -> Option A
  4. Quick Check:

    Use abs= for fixed tolerance in list approx comparison [OK]
Quick Trick: Use abs= for fixed tolerance in pytest.approx [OK]
Common Mistakes:
MISTAKES
  • Using rel= when abs= is needed
  • Not using pytest.approx for list comparison
  • Expecting exact equality for floats

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes