如何判断坐标集合中是否含指定x值?函数返回异常问题排查
has_x_value Function Returns False for Test Case b Let's break down what's going wrong here—this is a classic loop early-return mistake that trips up a lot of developers!
First, look at the loop logic in your function:
for i in x_values: if i == x: return True else: return False
The Root Cause
Here's exactly what happens when you call has_x_value({(14,14), (13,9), (13,16), (10,12)},10):
- Python converts your set to a list, but since sets are unordered, the first element in that list is likely
(14,14)(which is exactly what's happening in your test run). - The loop checks the first x-value (14) against your target (10). Since they don't match, the
elseclause immediately returnsFalse—the loop never gets to check the rest of the elements, including the(10,12)that should trigger aTruereturn.
Your first test case a works only by luck: the first element in the list happens to be (2,4), so the loop finds a match right away and returns True.
Quick Fixes
You only want to return False after checking every single element and finding no matches. Here are two solid ways to fix this:
Fix 1: Adjust the Loop Logic
Remove the else block inside the loop, and return False only once the loop finishes without finding a match. I also renamed a variable to avoid "shadowing" the input x (a good practice to prevent confusion):
def has_x_value(cs, x): tuple_convert = list(cs) x_values = [coord[0] for coord in tuple_convert] # Use `coord` instead of `x` to avoid shadowing for i in x_values: if i == x: return True # If we reach here, no matching x-value was found return False
Fix 2: Use Python's Built-in any() Function
This is a more concise and Pythonic approach. The any() function checks if any element in an iterable is True, which lets us simplify the function to one line:
def has_x_value(cs, x): return any(coord[0] == x for coord in cs)
This version skips unnecessary list conversions and directly checks each coordinate in the set.
Test the Fixed Code
If you run your original test cases with either fixed function, both a and b will return True as you expected.
内容的提问来源于stack exchange,提问作者JK7

