欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

笛卡尔积(评估表达式实现)

程序员文章站 2022-05-21 12:53:11
A×B=(∣x∈A∧y∈B) A \times B = \left( | x \in A ∧ y \in B \right) A×B=(∣x∈A∧y∈B)A = list(range(4))B = [chr(i) for i in range(65,65+4)]A,Bdef productExpr(*D): m = len(D) symbol_index = {i:chr(i) for i in rang...

A×B=(<x,y>xAyB) A \times B = \left( <x,y> | x \in A ∧ y \in B \right)

考虑到递归也好,还是别的方法,没办法在效率方面达到一个比较好的均衡,于是用推符号语句然后评估表达式的方式实现了这样的笛卡尔积

A = list(range(4))
B = [chr(i) for i in range(65,65+4)]
A,B

笛卡尔积(评估表达式实现)

def productExpr(*D,typekey='python'):
    m = len(D)
    symbol_index = {i:chr(i) for i in range(97,97+m)}
    symbol1 = "".join(["{}{}{}{}{}".format(" for " ,symbol_index[i]," in D[" ,i-97,"] ") for i in symbol_index])
    symbol2 = "".join(["{}{}".format(",",symbol_index[i]) for i in symbol_index])[1:]
    temp_expression = "{}{}{}{}{}{}".format("{","(",symbol2,")",symbol1,"}").replace("D",str(D))
    if typekey == "numpy": 
        expression = "{}{}{}".format("np.array(list(",temp_expression,"))")
    elif typekey == "python":
        expression = temp_expression
    expr = eval(expression)
    return expr

python set结构
笛卡尔积(评估表达式实现)
numpy 结构
笛卡尔积(评估表达式实现)

本文地址:https://blog.csdn.net/weixin_43069769/article/details/107158272