我很难理解以下代码的元素执行方式。目的是定义一个函数,该函数返回2组的笛卡尔乘积。应该使用下面的代码中的方法解决该问题。
我尝试查找类似的问题,但是由于我是编程和python的新手,所以我很容易卡住。
A = {1,2,3,4}
B = {3,4,5}
def setprod(m1,m2):
p=set()
for e1 in m1:
for e2 in m2:
p.add((e1,e2))
return p
setprod(A,B)
返回{(1, 3), (3, 3), (4, 5), (4, 4), (1, 4), (1, 5), (2, 3), (4, 3), (2, 5), (3, 4), (2, 4), (3, 5)}
笛卡尔积是包含两个集合中所有元素的有序对的集合。 A中的元素可以选择4种不同的方式,而B 3中的元素可以提供4x3 = 12的组合。
我看不出上面的代码为什么能做到这一点。
答案 0 :(得分:0)
如果您可以使用调试工具(也许可以安装pycharm并使用其调试器),则可以查看发生了什么情况。
让我们一起思考代码中正在发生的事情。
A = {1,2,3,4} #Step 1, load a set (1,2,3,4)
B = {3,4,5} #Step 2, load a set (3,4,5)
def setprod(m1,m2): #Step 4, define the function
p=set()
for e1 in m1:
for e2 in m2:
p.add((e1,e2))
return p
setprod(A,B) #Step 5, execute function with parameters
这时,如果我们想查看setprod是什么,我们将进入该函数。
p=set() #Steppedin, step 1 create empty set
for e1 in m1: #Steppedin, step 2, begin forloop iterating through m1,
#which contains (1,2,3,4); e1 is set to 1
for e2 in m2: #Steppedin, step 3 begin inner for loop
#iterating through m2, which contains (3,4,5),
#e2 is set to 3, e1 contains the value 1
p.add((e1,e2)) #Stepped in, step 4. add (m1[0],m2[0]), represented by
# (e1,e2) to the set.
return p
在步骤4中,下一步是同一行代码,但具有不同的寄存器值,e2不再是m2 [0],而是m2 [1]
p.add((e1,e2)) #Stepped in, step 5. add (m1[0],m2[1]), represented by
# (e1,e2) to the set where e1 = 1 and e2 = 4
。
p.add((e1,e2)) #Stepped in, step 6. add (m1[0],m2[2]), represented by
# (e1,e2) to the set where e1 = 1 and e2 = 5
这时我们返回到父循环。
for e1 in m1: #Stepped in, step 7.
#use m1[1] as e1 and repeat previous process but
#with the new e1 value set to 2
for e2 in m2: #Stepped in, step 8. e1 contains 2, e2 is set to 3
p.add((e1,e2))
(请注意,如果您正在调试它,我相信您只有在代码p.add的部分看到e2和e1的值,说e1在#处设置为某个值。进入步骤7,虽然不完全准确,但是对于了解正在发生的事情很有帮助。)