Home > Software engineering >  Returning a false statement in function
Returning a false statement in function

Time:10-18

I have a function that is supposed to validate whether a relation is a function.

This is my function:

def isFunction(A,B,f):
    ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
    for i in A:
        if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
            return False
    for i in f:
        if i not in A:
            return False
    return True

These are the taken inputs:

A = [1, 2, 3,]   ##change inputs according to the needs
B= [4,5]
f=[[1,4],[2,5],[3 ,4], [7, 4]]
print (isFunction(A,B,f))

I should be getting a False, which is correct but if I do another test case:

A = [1, 2, 3,]
B = [4, 5]
f = [[1,4], [2,5], [3,4]]
print('Returns: ', isFunction(A, B, f))

I also get a false statement now, but I should get a True statement instead. What is the error, and what do I do to change my function?

CodePudding user response:

The following modifications to your program result in what I suspect is the desired behavior

Option 1 iterate through ky instead of f in the second for loop:

def isFunction(A,B,f):
    ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
    for i in A:
        if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
            return False
    for i in ky:
        if i not in A:
            return False
    return True

Here's an alternative approach

Option 2: take i to be the first element from each pair of f rather than the entire pair.

def isFunction(A,B,f):
    ky = [i for i,j in f] ##fetching the first element of f and placing it in ky
    for i in A:
        if ky.count(i) != 1: ##checks whether the all elements of A have a unique image in B
            return False
    for i,_ in f:
        if i not in A:
            return False
    return True

Technically, both of these are flawed approaches in that they allow for functions whose domain consists only of a subset of A. For example, we get an incorrect "true" for the case of

A = [1,2]
B = [1,2]
f = [(1,1)]

Also, you seem to assume that pairs within f are distinct, i.e. each pair (i,j) can appear at most once in the "function" f.

Here's the approach that I would take. This assumes that the domain must consist of the entire set A and that pairs within f are distinct.

def isFunction(A,B,f):
    inputs = [i for i,_ in f]
    in_set = set(inputs)
    return in_set == set(A) and\
           len(in_set) == len(inputs)

The condition in_set == set(A) returns True iff the set of inputs is equal to the entirety of the domain A, and the condition len(in_set) == len(inputs) returns True iff each input i appears only once with a pair (i,j) from f.

  • Related