I am trying to used the Tree Structure for creating a permutation function:
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)
The output is like this: ['ABC ', 'ACB ', 'BAC ', 'BCA ', 'CAB ', 'CBA ']
But if I used 'AAB' as test data my output is: ['AAB ', 'AAB ', 'ABA ', 'ABA ', 'AAB ', 'AAB ', 'ABA ', 'ABA ', 'BAA ', 'BAA ', 'BAA ', 'BAA ']
The whole purpose for using tree structure to do permutation is if one of the char is duplicate, I can avoid overloading recursion function. click here for "tree structure algorithm"
- Any one has idea for adjusting the code to make the algorithm works?
- How to avoid using return ' ' in permutation function? According to my output, every permutation element has a SPACE. I tried to use '' or None, but the complier always give me error message.