B.Ahmed
B.Ahmed

Reputation: 28

How to fix this function please?

I need to code a function that takes as input a list of tuples, the number of tuples, and two numbers. This function should return True if the two given numbers exist in one of the tuples in our list.

For example : ma_fonction(l,n,i,j)

I tried this code:

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)

But it doesn't work. What should I add or change?


I tried this ( somehow i didnt copy all my work in my question )
This is my work:

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

Upvotes: 1

Views: 69

Answers (3)

dozerman
dozerman

Reputation: 307

This should work:

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

The reason your solution is not working is because you are returning False at the first element of the list that doesn't match with i and j. What you need to do is return False if and only if you looked in all the elements of the list and you couldn't find a match.

Upvotes: 0

wuyuup
wuyuup

Reputation: 13

The logic is that for each tuple in this list, check whether it contains the number i and j. If yes, then return True; if no, continue check the next tuple. Once you finish checking every tuple, and it turns out that there is no satisfied tuple, then return False.

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

Upvotes: 1

Shay Lempert
Shay Lempert

Reputation: 301

change your function to this:

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

You go over all tuples, and if i and j are in the tuple, you return True. If it went over all tuples and didn't find a match, we can be sure that we can return False.

And this implementation really doesn't need the parameter n

Upvotes: 1

Related Questions