Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function – encrypt key

I’m trying to create a function that encrypts a number of 4 digits insert by the user.

I was able to reach this:

while True:
    num = int(input('Insira um valor entre 1000 e 9999: '))
    if num<1000 or num>9999:
        print('Insira um valor válido.')
    else:
        break

num_str = str(num)

def encrypt(num):
    num_encrip = ''
    for i in num_str:
        match i:
            case '1':
                num_encrip = 'a'
            case '2': 
                num_encrip = '*'
            case '3':
                num_encrip = 'I'
            case '4':
                num_encrip = 'D'
            case '5':
                num_encrip = '+'
            case '6':
                num_encrip = 'h'
            case '7':
                num_encrip = '@'
            case '8':
                num_encrip = 'c'
            case '9':
                num_encrip = 'Y'
            case '0':
                num_encrip = 'm'
        print(num_encrip, end='')

encrypt(num_str)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And it works fine, but I know this isn’t very efficient and using lists should be better. And here I’m stuck because I can’t adapt the code above with lists…

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
chars = ['a', '*', 'I', 'D', '+', 'h', '@' 'c', 'Y', 'm']

while True:
    num = int(input('Insira um valor entre 1000 e 9999: '))
    if num<1000 or num>9999:
        print('Insira um valor válido')
    else:
        break

num_str = str(num)

def encrypt():
    pass

encrypt(num_str)

I’d writted so much thing inside the function encrip, but nothing works… I’m stuck… any help, please? I know I have to do a for loop… but what exactly?

Thank you.

>Solution :

With the 2 list, I’d suggest making a mapping from the numbers to the chars

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
chars = ['a', '*', 'I', 'D', '+', 'h', '@', 'c', 'Y', 'm']
correspondances = dict(zip(nums, chars))

def encrip2(value):
    num_encrip = ''
    for c in value:
        num_encrip += correspondances[int(c)]
    print(num_encrip)

And as the indexes are ints, you can directly use them as indexes into the chars

chars = 'ma*ID+h@cY'
def encrip2(value):
    num_encrip = ''
    for c in value:
        num_encrip += chars[int(c)]
    print(num_encrip)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading