Home > database >  Function - encrypt key
Function - encrypt key

Time:11-28

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)

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.

CodePudding user response:

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)
  • Related