如何修复判断元组列表中两数是否同组的Python函数?
Fixing Your
ma_fonction Python Function Let's break down the issues in your current code and fix them step by step:
1. Critical Logic Error in the Loop
Your current code returns False as soon as it hits a tuple that doesn't contain both i and j. That means it only checks the first tuple and stops there—completely missing any matches in later tuples (like the (5,2) tuple in your test case).
2. Typo & Unnecessary Variable
You have a typo (cheker instead of checker), and the checker variable is actually redundant since you're returning immediately when a match is found.
Corrected Code
def ma_fonction(l, n, i, j): # First validate the input conditions if i == j or not (0 <= i <= n-1) or not (0 <= j <= n-1): return False # Check every tuple in the list for item in l: if i in item and j in item: return True # If no tuple contains both i and j after checking all return False
How This Works
- Input Validation: We first check if
iandjare valid (distinct, within the 0 to n-1 range). If not, we immediately returnFalse. - Loop Through Tuples: We iterate through every tuple in the list. As soon as we find one that contains both
iandj, we returnTrue. - Final Return: If we finish checking all tuples and haven't found a match, we return
False.
Testing Your Example
When you run ma_fonction([(0,1), (5,2), (4,3)], 6, 2, 5):
- The input validation passes (2≠5, both are between 0 and 5).
- It checks the first tuple
(0,1)—no match, so moves to the next. - It checks the second tuple
(5,2)—both 2 and 5 are present, so returnsTrueas expected.
内容的提问来源于stack exchange,提问作者B.Ahmed
相关产品推荐
相关产品推荐

