Program to check whether domain and range are forming function or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of data say x, represents a domain and a list of data y (size of y is same as size of x), represents a range. We have to check whether x -> y is a function or not. Here we are considering all elements in x and y are positive.

So, if the input is like x = [1,3,2,6,5] y = [1,9,4,36,25], then the output will be True, because for each x, the corresponding y is its square value here, so this is a function.

To solve this, we will follow these steps −

Here we are considering a simple set of steps. This problem can be solved in some complex way also.

  • mp := a new map
  • for i in range 0 to size of x, do
    • a := x[i]
    • b := y[i]
    • if a is not in mp, then
      • mp[a] := b
    • otherwise,
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

def solve(x, y):
   mp = {}
   for i in range(len(x)):
      a = x[i]
      b = y[i]
      if a not in mp:
         mp[a] = b
      else:
         return False
   return True

x = [1,3,2,6,5]
y = [1,9,4,36,25]
print(solve(x, y))

Input

[1,3,2,6,5], [1,9,4,36,25]

Output

True
raja
Published on 12-Oct-2021 07:56:35

Advertisements