i want to print permutations of a string in a sorted way. and i am not allowed to use itertools and i must do it with recursion.
this is the code that i created for this purpose but it is very slow as for 10 characters it takes 200s to print all answers! i want to make it faster to do it in 10s . any help?
n = int(input()) # n is the number of characters
1 <= n <= 10
elements0 = str(input()) # it will be in this format : A B C D E F G
elements = elements0.split()
def translate(elements) :
i = 0
while i < n :
elements[i] = int(i)
i = i + 1
return elements
elements = translate(elements)
def factor(elements,i):
elements = elements[:]
if i == len(elements) - 1:
list.append(elements)
return elements
else:
for j in range(i,len(elements)):
elements[i], elements[j] = elements[j], elements[i]
factor(elements, i + 1)
elements[i], elements[j] = elements[j], elements[i]
list = []
factor(elements,0)
list = sorted(list)
def untranslate(list,n) :
from math import factorial
i = 0
while i < factorial(n) :
k = 0
while k < n :
if list[i][k] == 0 :
list[i][k] = elements0[0]
if list[i][k] == 1 :
list[i][k] = elements0[2]
if list[i][k] == 2 :
list[i][k] = elements0[4]
if list[i][k] == 3 :
list[i][k] = elements0[6]
if list[i][k] == 4 :
list[i][k] = elements0[8]
if list[i][k] == 5 :
list[i][k] = elements0[10]
if list[i][k] == 6 :
list[i][k] = elements0[12]
if list[i][k] == 7 :
list[i][k] = elements0[14]
if list[i][k] == 8 :
list[i][k] = elements0[16]
if list[i][k] == 9 :
list[i][k] = elements0[18]
k = k + 1
i = i + 1
return list
list = untranslate(list,n)
while True :
if list == [] : break
else:
i=0
row = str()
while i < n :
row = row + str(list[0][i])
i = i + 1
list.pop(0)
print(row) # This should be in this format : ABCDEFG
and another point : the way i want to sort is not ABCD ... (alphabetic) . character's values are as they appear in elements0 . for example if elements0 is BA , it must be printed BA AB .
Well, since this is homework, I can give you a version that varies slightly from what you're trying to achieve.
Remember in recursion, you need two things:
Here is the code
def getPermutations(string):
if len(string) == 1: # Base Case
return [string]
else: # Not base case
result = []
for i in range(len(string)):
candidate = string[i]
remaining = string[0:i] + string[i+1:]
babies = getPermutations(remaining) # Faith!
for word in babies:
result.append(candidate + word)
return result
This definitely does not take 200s for "ABCD". The code is self documenting, so you should be able to figure out what's being done here.
Here's a sample run.
>>> myPerms = sorted( getPermutations("ABC") )
>>> for p in myPerms: print p
...
ABC
ACB
BAC
BCA
CAB
CBA
Note that this won't work if the string has duplicate entries (eg "AABC"). Good luck with your homework!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.