You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复判断元组列表中两数是否同组的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 i and j are valid (distinct, within the 0 to n-1 range). If not, we immediately return False.
  • Loop Through Tuples: We iterate through every tuple in the list. As soon as we find one that contains both i and j, we return True.
  • 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):

  1. The input validation passes (2≠5, both are between 0 and 5).
  2. It checks the first tuple (0,1)—no match, so moves to the next.
  3. It checks the second tuple (5,2)—both 2 and 5 are present, so returns True as expected.

内容的提问来源于stack exchange,提问作者B.Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:27:51