Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing set of functions from finite set to finite set

Tags:

python

I'm wondering is there a good way to create a set of functions from a finite set A to the set of number from 1 to n in python?

For example, if A={a,b,c,d,e,f,g} and n=2, then the set of functions can be thought of as all possible subsets of A. But how would you implement it in python?

like image 821
small_angel Avatar asked Nov 29 '25 00:11

small_angel


1 Answers

here is a generator of all the functions from set A to set B:

from functools import partial
from itertools import product

def f_generator(A, B):
    def f_template(d, x):
        return d[x]
    for b_values in product(B, repeat=len(A)):
        yield partial(f_template, dict(zip(A, b_values)))

For example, you can use it in the following way:

A = ["a", "b"]
B = [1, 2, 3]
for f in f_generator(A, B):
    # f is the function, and you can use it as you expect: y=f(x)
    print(f'f("a")={f("a")}, f("b")={f("b")}')

Which prints the following output (one line for every function):

f("a")=1, f("b")=1
f("a")=1, f("b")=2
f("a")=1, f("b")=3
f("a")=2, f("b")=1
f("a")=2, f("b")=2
f("a")=2, f("b")=3
f("a")=3, f("b")=1
f("a")=3, f("b")=2
f("a")=3, f("b")=3

You can also have a list (or a set) of all the possible functions (be careful: there could be many!!):

functions = list(f_generator(A, B))
f = functions[3] # the 4th function

You can now use f as a normal function (for example you can do f("b"))

like image 130
Riccardo Bucco Avatar answered Nov 30 '25 14:11

Riccardo Bucco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!