There is a table of permutations of characters in the string (eight characters). table = [6, 8, 2, 4, 3, 7, 5, 1] . And the text text = 'qwertyui' , I do the permutation in this way: perm = ''.join(text[x - 1] for x in table) and get the output string yiwreutq , that is, the first character from the text string, becomes the sixth, second - the eighth, etc, i.e. from the qwertyui string, the yiwreutq string is yiwreutq .

But with the inverse permutation, difficulties arose, came up with only this option: txt = ''.join([i for sub in sorted(zip(perm, table), key=lambda t: t[1]) for i in sub[0]]) , although it seems that there is a much easier option. How can you also implement the reverse permutation to get qwertyui from yiwreutq again?

Thank.

  • table.reverse () does not help? - Taarim
  • @Taarim No, of course. - Enikeyschik

3 answers 3

 ''.join([new_str[table.index(i+1)] for i in range(len(table))]) 

    Try to use the compliance table:

     In [90]: tab = list(zip(map(lambda x: x-1, table), range(len(table)))) In [91]: tab Out[91]: [(5, 0), (7, 1), (1, 2), (3, 3), (2, 4), (6, 5), (4, 6), (0, 7)] In [92]: back = ''.join(perm[b] for _,b in sorted(tab)) In [93]: back Out[93]: 'qwertyui' 
       txt = table[:] for k,i in enumerate(table): txt[i-1]=text[k] txt = ''.join(txt)