throw questions
Find the full permutation and combination of any string, such as a='123', output 123, 132, 213, 231, 312, 321.
solution
# character exchange at any two positions in the string def str_replace(str, x, y): if x == y: return str x_val = str[x:x+1] y_val = str[y:y+1] if x < y: str = str[0:x] + y_val + str[x+1:y] + x_val + str[y+1:len(str)] else: str = str[0:y] + x_val + str[y+1:x] + y_val + str[x+1 :len(str)] return str #recursive result def str_sort(str,x): if x == len(str): #When x is the maximum length of the string, return the result of the current character exchange global str_list str_list.append(str) return for i in range(x,len(str)): if str[i] not in str[x:i]: str = str_replace(str,i,x) #Recursively traverse the i-th character, str_sort(str,x+1 ) str = str_replace(str,x,i) #Restore the original order of the string for the next traversal else : return s = ' abcc ' global str_list str_list = [] str_sort(s,0) print (len (str_list), str_list)
Compared with the method with repetition, it is just one more step, that is, before traversing the i-th element, make a judgment, that is, whether the character that needs to be exchanged is already 'heading', if so, ignore it and continue to execute