I'm learning about types of function in discrete maths. I like to learn by exploring concepts through computer code. I came across the following code purporting to determine whether a function is injective:
def is_injective(function):
# Check if the function is injective (one-to-one)
codomain_set = set(function.values())
return len(codomain_set) == len(function)
# Example usage
domain = ["A","B","C"] # Replace with your domain
codomain = [1,2,3,4] # Replace with your codomain
function = {
"A": 1, # Replace with your function mapping
"B": 2, # Replace with your function mapping
"C": 4, # Replace with your function mapping
}
if is_injective(function):
print("The function is injective (one-to-one).")
I'm having a bit of trouble understanding how this works or whether it is correct. In is_injective(), codomain_set seems to create a set from the function values (which I think represent the range?). I assume creating a set is to remove duplicates.
However, I'm not seeing how comparing a set comprising the range values to the number of values from the domain in the mapping is equivalent to the standard mathematical definition of an injective function.
Can anyone please provide some clarification?
The way I see this is function is an array of something like this.
function = ((1,A),(2,B),(3,C),(4,B)) [not injective as function.2 = function.4 = B]
Then function.values() is a list (A,B,C,B). A list can have multiple objects.
set() is a function that turns the list into a set that can not have multiple objects. So set(A,B,C,B) will return (A,B,C)
Now function has length 4. And function.values() has length 4. but codomain_set = (A,B,C) has length 3 so the they are inequal. The only way that can happen is if function.values() had repeated elements that got stripped. And that means the function was not injective.
On the other hand if the function = ((1,A),(2,B), (3,C), (4,D)) and was injective then function.values = (A,B,C,D) has no repeated values. So set(A,B,C,D) will return (A,B,C,D) and nothing is stripped and function, function.values(), and codomain_set=set(function.values()) will all be equal to 4.
So despite my initial critique of this being bad code and useless, I've changed my mind and now think it is valid.
...... but it does depend on the coding language (which must have a set() function that strips out repeated list terms.
======
Now this will ONLY work on functions with finite domains. Infinite domains we could easily have $f:\mathbb Z \to \mathbb Z$ $f(x) = x^2$ were the domain is $\mathbb Z$ and function.values() is $\{....,16,9,4,1, 0 , 1, 4, 9, 16,....\}$ and set(function.values) DOES strip it to $\{0,1,4,9,16,.....\}$ and but we the length of both even after stripping are both equal and infinite.
....
Then again... I can only program finite domains anyway, I think.