简体   繁体   English

DFS在python中打印字符串的所有排列

[英]DFS to print all permutations of a string in python

I am using DFS to print all the permutations but I have a small pythonic mistake wrt return value from foo. 我正在使用DFS打印所有排列,但是我从foo返回了一个小的pythonic错误wrt返回值。

For the key '1', I want the return value of foo to be [[1,2,3] [1,3,2]] but it is currently [1,2,3,1,3,2]. 对于键“ 1”,我希望foo的返回值为[[1,2,3] [1,3,2]],但目前为[1,2,3,1,3,2]。 I tried using result.append but it didn't work. 我尝试使用result.append,但是没有用。

data = [1, 2, 3]

def foo(key, dict_data, output):
  result = []
  if len(output) == len(dict_data.keys()):
    return output
  values = dict_data[key]
  for value in values:
    if value not in output:
      result += foo(value, dict_data, output + [value])
  return result

dict_data = {}
for i in range(len(data)):
  dict_data[data[i]] = data[0:i] + data[i+1:]
result = []
for key in dict_data.keys():
  result += foo(key, dict_data, [key])
for i in range(0, len(result), len(data)):
  print(result[i:i+len(data)])

Basically I don't want to use the last 2 lines of my code which is superfluous. 基本上,我不想使用多余的两行代码。

Instead of return output you should do return [output] , so that the gathered numbers are put in their own list. 而不是return output您应该return [output] ,以便将收集到的数字放在自己的列表中。 Then when you do result += you will not be adding individual numbers, but the list, which is what you want. 然后,当您得到result +=时,您将不需要添加单个数字,而是要添加列表。

Note that your use of a dictionary is overly complex, and only brings benefit for the first level, because each key includes all values except one, so you'll be iterating all values except one, which is not much of a gain. 请注意,您对字典的使用过于复杂,只会给第一级带来好处,因为每个键都包含除一个以外的所有值,因此您将迭代除一个以外的所有值,这没有什么好处。

Apart from the fact that itertools has methods for what you want, you could use a set to keep track of which values are still available for selecting: 除了itertools具有所需方法之外 ,您还可以使用一set来跟踪哪些值仍可供选择:

def foo(set_data, output):
  if len(set_data) == 0:
    return [output]
  result = []
  for value in set_data:
    result += foo(set_data - set([value]), output + [value])
  return result

data = [1, 2, 3]
set_data = set(data)
result = foo(set_data, [])
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM