Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether domain and range are forming function or not in Python
Suppose we have a list of data x that represents a domain and a list of data y (same size as x) that represents a range. We need to check whether the mapping x ? y forms a valid function. In mathematics, a function is a relation where each input (domain element) maps to exactly one output (range element).
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 each element in x maps to exactly one corresponding element in y (in this case, each x maps to its square value).
Algorithm
To solve this problem, we will follow these steps:
- Create an empty dictionary
mpto store domain-range mappings - For each index i from 0 to length of x:
- Get domain element:
a = x[i] - Get range element:
b = y[i] - If
ais not in dictionary:- Store the mapping:
mp[a] = b
- Store the mapping:
- If
aalready exists with different value:- Return False (not a function)
- Get domain element:
- Return True (valid function)
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:
if mp[a] != b:
return False
return True
# Test case 1: Valid function (each x maps to x^2)
x = [1, 3, 2, 6, 5]
y = [1, 9, 4, 36, 25]
print("Test 1:", solve(x, y))
# Test case 2: Invalid function (1 maps to both 10 and 20)
x2 = [1, 2, 1, 3]
y2 = [10, 20, 20, 30]
print("Test 2:", solve(x2, y2))
Test 1: True Test 2: False
How It Works
The algorithm uses a dictionary to track which domain elements have been seen and their corresponding range values. If we encounter a domain element that already exists but maps to a different range value, we return False because this violates the function definition.
Key Points
- A function requires each domain element to map to exactly one range element
- Multiple domain elements can map to the same range element
- If any domain element maps to multiple range elements, it's not a function
- The algorithm has O(n) time complexity where n is the length of the lists
Conclusion
This program efficiently checks if a domain-range mapping forms a valid function by using a dictionary to track mappings. The key insight is that functions require each input to have exactly one output, which we verify by detecting duplicate domain elements with different range values.
