写错 Python 部分代码,结果让我想不明白
问题比较难描述。我是新手,本来我是用 Ruby 写全排列算法生成器的,然后想看 Python 怎么写。我不懂 Python,所以看别人怎么用 yield 也就随便用。问题出在我写错的最后一句:print(‘,’.join(str(o))),打印的结果我实在看不懂,或许是我不懂 yield 的流程。是我的 yield 哪里写错了吗?
# 生成数组[1,2,3,4]的全部元素的全排列 def scan(src, m, n): if (m == n): yield src else: for i in range(m, (n+1)): # 交换 tmp = src[m] src[m] = src[i] src[i] = tmp # 递归 for _ in scan(src, (m+1), n): yield _ # 恢复交换前 tmp = src[m] src[m] = src[i] src[i] = tmp def perm_core(src): n = len(src) - 1 for _ in scan(src, 0, n): yield _ # main list = [i for i in range(1, 5)] for o in perm_core(list): # ~ w = [str(y) for y in o] # ~ print (','.join(w)) # 正确代码 print(','.join(str(o))) # 错误代码
打印结果