我正在尝试使用树结构来创建排列函数:
import copy
def myPermutation (newString, newDict):
if sum(newDict.values()) == 0:
return ' '
else:
curDict = copy.deepcopy(newDict)
nextDict = copy.deepcopy(newDict)
results = []
for i in range(len(newString)):
curChar = newString[i]
if curDict[curChar] == 0:
continue
else:
print(curDict, ' -> ', curChar)
nextDict[curChar] -= 1
print(nextDict)
for p in myPermutation(newString, nextDict):
results.append(curChar+p)
# myPermutation(newString, nextDict)
# results.append(curChar)
nextDict=copy.deepcopy(newDict)
return results
def curDict (newString):
myDict = dict()
for char in newString:
myDict[char] = myDict.get(char,0) + 1
return myDict
newString = 'ABC'
newDict = curDict(newString)
test = myPermutation(newString, newDict)
print(test)
输出如下: [' ABC',' ACB',' BAC',' BCA'' CAB' ,' CBA']
但如果我使用了AAB'作为测试数据,我的输出是: [' AAB',' AAB',' ABA',' ABA'' AAB' ,' AAB' ABA' ABA',' BAA'' BAA' ,' BAA',' BAA']
使用树结构进行排列的整个目的是如果其中一个char是重复的,我可以避免重载递归函数。 click here for "tree structure algorithm"
答案 0 :(得分:0)
好吧,我想通了,根据算法,我需要将'inputString'转换为一个独特的Char String,将'AAB'转换为'AB' 然后将带有dict的不同Char字符串传递给置换函数。 这是新代码:
A B
_ _ _ _ _ _ _ _ _ _
DCS000111 1
DCS000112 2
DCS000113 3
DCS000115 1
DCS000119 2
答案 1 :(得分:0)
对于 SPACE 问题,我可以简单地使用:
for items in test:
print(items.strip(), end=' ')
但是,无论如何我可以直接进行排列函数吗?