如何修复这个函数?

2024-04-27 05:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个函数,将元组列表、元组数和两个数字作为输入。如果两个给定的数字存在于我们列表中的一个元组中,这个函数应该返回True。你知道吗

例如:ma_fonction(l,n,i,j)

  • l:元组列表
  • ij两个介于0n-1i != j之间的数字

我试过这个代码:

def ma_fonction(l,n,i,j):
    checker = False
    for item in l :

        if ( i in item and j in item ):
            cheker = True
            return True 
        else: 
            return False

ma_fonction([(0,1), (5,2), (4,3)], 6, 2, 5)

但它不起作用。我应该添加或更改什么?你知道吗


我试过这个(不知怎么的,我没有抄我问题中的所有作品)
这是我的工作:

def ma_fonction(l,n,i,j):
    checker = False
    if((i!=j )and (0<=i<=n-1 )and( 0<=j<=n-1) ):
        for item in l :

            if ( i in item and j in item ):
                cheker=True
                return True 
            else: 
                return False

Tags: and函数infalsetrue列表returnif
3条回答

逻辑是,对于这个列表中的每个元组,检查它是否包含数字i和j。如果是,则返回True;如果不是,则继续检查下一个元组。一旦检查完每个元组,发现没有满意的元组,则返回False。你知道吗

def ma_fonction(l,n,i,j):
    for item in l :
        if ( i in item and j in item ):
            return True 
    return False

将函数更改为:

def foo(l,n,i,j):
    for item in l: 
        if (i in item and j in item):
            return True 
    return False

遍历所有元组,如果i和j在元组中,则返回True。 如果它遍历了所有元组,但没有找到匹配项,我们可以确定返回False。你知道吗

这个实现实际上不需要参数n

这应该起作用:

def ma_fonction(l,n,i,j):
    for item in l :
        if ( i in item and j in item ):
            return True 
    return False

解决方案不起作用的原因是,在列表中与i和j不匹配的第一个元素处返回False。您需要做的是在查找列表中的所有元素但找不到匹配项时才返回False。你知道吗

相关问题 更多 >