Как добавить каждую другую букву случайной буквой? - PullRequest
0 голосов
/ 08 января 2019

Я пытаюсь добавить каждые две буквы случайную букву в строку, используя класс и функцию

class Encryption():

    def __init__(self,seed):

        # Set a random seed and a self.seed attribute
        self.seed = seed

        # Create an empty string attribute to hold the encrypted phrase
        self.encrypted_phrase = ''

        # Use the string and random libraries to create two attributes
        # One is the correct alphabet, another is a shuffled alphabet:

        self.correct_alphabet = list(string.ascii_lowercase)
        self.shuffeled_alphabet = random.sample(correct_alphabet, seed)

    def encryption(self,message):

        appended_message = list(message)       
        for let in list(range(0, len(message), 2)):
            if let in self.correct_alphabet:
                appended_message.append(self.shuffeled_alphabet)
        return appended_message

Так что, если я сделаю

e2 = Encryption(3)
e2.encryption(hello)

не получается со следующим сообщением

NameError                                 Traceback (most recent call last)
<ipython-input-24-505d8a880fb2> in <module>
----> 1 e2.encryption(message=hello)

NameError: name 'hello' is not defined

Что я делаю не так?

Ответы [ 2 ]

0 голосов
/ 08 января 2019

Ваша ошибка вызывает ваш код с переменной вместо строки. Смотрите комментарий или другой пост.


Вы также можете упростить и ускорить, а также исправить свою логику с помощью диктов - вы создаете один диктов для кодирования, а обратный дикт для декодирования. Вы переводите каждый символ с помощью диктовок и '' .join впоследствии, используя троицу и по модулю, чтобы изменять только каждую every букву:

import random
import string

class Encryption(): 
    def __init__(self,seed):
        # Set a random seed and a self.seed attribute
        random.seed(seed)
        source=string.ascii_lowercase
        crypt = random.sample(source,k=len(source))

        # one dict to encrypt
        self.enc = {k:v for k,v in zip(source,crypt)}

        # reverse crypt to decrypt 
        self.dec = {k:v for v,k in self.enc.items()}

    def encryption(self,message,every=1):
        return self.do_it(self.enc,message,every) 

    def decryption(self,message,every=1):
        return self.do_it(self.dec,message,every)  

    def do_it(self, mapper, message, every):
        # replace unknown characters (after lowercasing) by ?
        return ''.join( (mapper.get(c,"?") if i % every == 0 else c 
                         for i,c in enumerate(message.lower())))

Тест:

crypto_1 = Encryption(42)
crypto_2 = Encryption(42)
crypto_3 = Encryption(99)

word = "apple1234juice"
code = crypto_1.encryption(word,2)
print(word,code,crypto_1.decryption(code,2),"Same crypto")
print(code,crypto_2.decryption(code,2),"Different crypto, same seed")
print(code,crypto_3.decryption(code,2),"Different crypto, other seed")

Вывод (переформатирован - сохраняется каждый второй символ):

                    p l 1?3?j i e     # are kept as is

apple1234juice     upllh1?3?jgiae     apple1?3?juice     Same crypto
upllh1?3?jgiae     apple1?3?juice                        Different crypto, same seed
upllh1?3?jgiae     gpnlf1?3?jcize                        Different crypto, other seed
0 голосов
/ 08 января 2019

hello должна быть строкой, так как она не является переменной.

Попробуйте e2.encryption("hello") или что-то подобное.

Таким образом, ваш полный пример кода будет:

e2 = Encryption(3)
e2.encryption("hello")
...