Output values are leaving without space

Asked

Viewed 48 times

1

I have the following problem to solve:

Cryptography (Greek: kryptós, "hidden", and gráphein, "written") is the study of the principles and techniques by which information can be transformed from its original form to another unreadable, so that it can be known only to its addressee (holder of the "secret key"), which makes it difficult to read by anyone unauthorized (Wikipedia).

One of the simple encryption techniques is the substitution cipher, which is composed of:

Normal alphabet;

Alphabet for the cipher;

The encrypted message

As a result of the decryption process we have the original message. Then implement a program that gives these 3 components to return the original message. Each of these components is on a separate line.

To solve the problem, I coded the following algorithm:

def descriptografar_texto(alfabeto_normal,alfabeto_cifrado,mensagem):    
    dic = {}
    alfa_norm = list(alfabeto_normal)
    alfa_cifr = list(alfabeto_cifrado)
    frase = ''
    for letra1,letra2 in zip(alfa_cifr,alfa_norm):
        dic[letra1] = letra2
    for letra in mensagem:
        if letra in dic:
            frase += dic.get(letra)
    return frase

a = input()
b = input()
c = input()

print(descriptografar_texto(a,b,c))

The desired exit is a sentence, however, my exit is leaving without spaces between words. How can I fix this?

  • 1

    The postage has been arranged.

1 answer

1


I added a else when the letra not in the dictionary he put a space.

if letra in dic:            
                frase += dic.get(letra)
            else:
                frase += " "

Follow the full code:

def descriptografar_texto(alfabeto_normal,alfabeto_cifrado,mensagem):

    dic = {}
    alfa_norm = list(alfabeto_normal)
    alfa_cifr = list(alfabeto_cifrado)
    frase = ''
    for letra1,letra2 in zip(alfa_cifr,alfa_norm):
        dic[letra1] = letra2
    for letra in mensagem:
        if letra in dic:            
            frase += dic.get(letra)
        else:
            frase += " "

    return frase

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

b = ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

c = "mlhhz jfv olfxfiz"

print(descriptografar_texto(a,b,c))

Exit:

nossa que loucura

  • 1

    Note that I put the lowercase alphabet so if you type a uppercase letter will be displayed a space. The same happens for numbers and special characters. To fix this the lists a and b need to be updated.

  • Thank you! It worked perfectly.

  • That’s great, I’m really happy to help you. Hug and see you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.