How to implement a permutation algorithm in Python?

2

I'm trying to implement a permutation algorithm in Python.

It receives as input a phrase and a key (numeric value) that matches the amount of letters each group should have, numerical sequence from 1 to the value of the key.

Here is an example of data entry:

Input Phrase:

  

"Python is the best language !!"

Input key:

  

5

Input Sequence:

  

4 2 5 1 3

Expected output:

  

Hyopt
  meena
  rhllo
  unaig
  ! gm

It follows my attempt, but without result, because I am not able to implement and do the division by groups to obtain the result illustrated in the example.

Code:

contador = 0            
frase = input('Digite uma frase: ').upper
chave = int(input('Digite a chave: '))
seq = []

while contador <= chave:    
  seq.append(int(input('Digite o número da sequência: ')))

frase = frase.split()
frase = ''.join(frase)
    
asked by anonymous 19.09.2017 / 16:41

1 answer

1

Separation of text into groups can be done through a list comprehension, accessing i:i+key positions of text, where i ranges from 0 to text length, with step equal to key . When the last group does not have the required number of characters, * is added using the ljust method. After that, the groups are traversed and the permutation between the characters is done.

# Frase de entrada:
text = input("Entre com uma frase: ")

# Chave de entrada:
key = int(input("Entre com uma chave: "))

# Sequência de entrada:
sequence = []
for i in range(key):
    sequence.append(int(input("Entre com um número da sequência: ")))

# Remove os espaços em branco do texto:
text = text.replace(" ", "")

# Divide o texto em grupos definidos pela chave:
groups = [text[i:i+key].ljust(key, "*") for i in range(0, len(text), key)]

# Percorre os grupos gerando os novos grupos:
result = []
for group in groups:
    output = ""
    for i in sequence:
        output += group[i-1]
    result.append(output)

print(result)

With the entries presented in the question, the output is:

['hyoPt', 'méena', 'rhllo', 'unaig', '!e!gm']
  

See working at Ideone .

    
19.09.2017 / 20:25