【问题标题】:Why doesn't this modified Cartesian Product function for Python work?为什么这个修改后的 Python 笛卡尔积函数不起作用?
【发布时间】:2016-02-12 03:01:22
【问题描述】:

理想情况下,输入是[1,2],输出是所有组合[[1,1], [2,2], [1,2], [2,1]]。基本上,打印所有可能的替换组合。

def cart(lst):
   if lst == []:
      return [[]]

   return [x[i:] + [lst[0]] + x[:i] for x in cart(lst[1:]) for i in range(len(x)) ]

l = [1,2,3] 
print cart(l)

返回

[]

以更易于阅读的形式,代码基本上是这样写的:

for x in cart(lst[1:]):
   for i in range(len(x)):
      return x[i:] + [lst[0]] + x[:i]

如果我们假设输入为[1,2,3] 的递归情况,那么 cart([2,3]) 应该产生[[2,3], [3,2], [2,2], [3,3]],因此对于递归步骤,我们希望在每个可能的位置插入1。 (此代码可能缺少 111 案例。)

代码看起来逻辑正确,但输出一个空字符串。

有什么遗漏还是我没有正确解决问题?

编辑

实际上,我意识到代码会稍微复杂一些:

def cart(lst):
    if len(lst) <= 1:
        return lst
    else:
        return [x[i:] + [lst[j]] + x[:i] for x in cart(lst[1:]) for j in range(len(lst)) for i in range(len(x))]

虽然这仍然奇怪地返回一个空列表。我的直觉是我错过了一个基本案例。

编辑

这与我的基本情况有关。修改后的代码:

def cart(lst):
    if len(lst) <= 1:
        return [lst]
    else:
        return [x[i:] + [lst[j]] + x[:i] for x in cart(lst[1:]) for j in range(len(lst)) for i in range(len(x))]

l = [1,2,3]
print cart(l)

但现在又回来了

[[3, 2, 1], [2, 1, 3], [3, 2, 2], [2, 2, 3], [3, 2, 3], [2, 3, 3 ], [3, 3, 1 ], [3, 1, 3], [3, 3, 2], [3, 2, 3], [3, 3, 3], [3, 3, 3]]

现在好多了,虽然输出缺少集合。似乎又是一个基本案例问题。

【问题讨论】:

  • 如果您找到了问题的答案,请照此发布并接受。它对每个人都有好处。
  • 所以你想实现itertools.product?
  • 在这种情况下你可以研究documentation中的那个,那里有一个纯python版本,你可以使用它或它的一些变体来满足你的口味

标签: python product cartesian


【解决方案1】:

在这里找到答案 Algorithm for recursive function for permutations with replacement in python

def permutations_with_replacement(k,n):
         # special case (not part of recursion)
         if k == 0:
            return []

         if k == 1:
            return [[n[i]] for i in range(len(n))]

         else:
            # Make the list by sticking the k-1 permutations onto each number 
            # we can select here at level k    
            result = []
            # Only call the k-1 case once, though we need it's output n times.
            k_take_one_permutations = permutations_with_replacement(k-1,n)  

            for i in range(len(n)):
                for permutation in k_take_one_permutations:
                    result.append([n[i]]+permutation)   
            return result

         print permutations_with_replacement(3,2)

print permutations_with_replacement(3, [1,2,3])

看来我试图采用列表本身的递归大小写,而不是组合的大小。

我想知道解决方案是否可以通过在列表中重复出现而不是组合的大小来实现。

【讨论】:

    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 2013-07-19
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2012-02-24
    • 2023-03-17
    相关资源
    最近更新 更多