python non recursive full permutation implementation
- 2020-05-30 20:25:45
- OfStack
I'm just getting started with python, and I'm currently looking at the functions section 1. Combined with the array operation, write a non - recursive full array generation. The principle is the insertion method, that is, in an existing arrangement with n elements, the elements added after are inserted in each position of the first, middle and last in order to generate n+1 new full arrangement. Because Python is easy to cut arrays or strings and merge, the program saves a lot of code.
def getArrayInsertCharToStr(STR,CHAR):
arr =[]
s_len = len(STR)
index =0
while index <= s_len:
# Split string
arr.append(STR[:index]+CHAR+STR[index:s_len])
index = index + 1
return arr
def getArrayInsertCharToArray(array,CHAR):
index = 0
re_array = []
while index < len(array):
re_array = re_array + getArrayInsertCharToStr(array[index],CHAR)
index = index + 1
return re_array
def getPermutation(STR):
resultArr = [STR[0]]
for item in STR[1:]:
resultArr = getArrayInsertCharToArray(resultArr,item)
return resultArr
print(getPermutation('abc'))