Zasadniczo mam funkcję, która będzie bardzo po prostu zaszyfrować wiadomość.

def encrypt(message):
    alphabet = ["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"]
    key = ["4","x","z","@","%","b","j","q","(","ƒ","¥","µ","˚","nå","ø","π","å","œ","¢","∞","∫","µ","≈","`","¬","…"]
    new_message = ""
    for x in range(0,len(message)):
        new_message = message.replace(message[x],key.index[alphabet.index(message[x])])
    return new_message

print(encrypt(input("What would you like to encrypt").lower()))

Powinno to zrobić list i zastąpić go znakiem z tym samym indeksem w klawisza listy, jednak otrzymuję błąd:

TypeError: 'builtin_function_or_method' object is not subscriptable
1
Sumtinlazy 26 czerwiec 2017, 21:50

3 odpowiedzi

Najlepsza odpowiedź

Wreszcie użycie przypadku dla {X0}}!

def encrypt(message):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    key = '4xz@%bjq(ƒ¥µ˚nåøπ圢∞∫µ≈`¬'
    table = str.maketrans(alphabet, key)

    return message.translate(table)

print(encrypt('asdsaewqeq')) # 4œ@œ4%µπ%π

Zauważ, że jeden z twoich wpisów w key składa się z dwóch znaków. Jeśli jest to intencjonalne i chcesz zastąpić pojedynczy znak z dwoma, możesz ręcznie utworzyć tabelę tłumaczenia.

table = dict(zip(map(ord, alphabet), key))
2
Jared Goguen 26 czerwiec 2017, 19:52

Proponuję użyć pośredniego dict do stworzenia mapowania {x1}} element listy z key Item:

>>> alphabet = ["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"]
>>> key = ["4","x","z","@","%","b","j","q","(","ƒ","¥","µ","˚","nå","ø","π","å","œ","¢","∞","∫","µ","≈","`","¬","…"]

# Your `dict` object with the mapping between both the list
>>> encryption_dict = dict(zip(alphabet, key))

Następnie użyj powyższego słownika z str.join(...), aby przekształcić ciąg. Na przykład:

>>> my_str = 'stackoverflow'

#  Transform the string using the `dict` and join the chars to form single string           
>>> new_str = ''.join(encryption_dict.get(s, s) for s in my_str)
#                                            ^
#        to return same character if not present in alphabet list

>>> print(new_str)
¢∞4z¥øµ%œbµø≈
2
Moinuddin Quadri 26 czerwiec 2017, 19:04

key.index() Pobiera wartość i zwraca indeks i używa () nie [], więc musisz naprawić tę linię:

new_message = message.replace(message[x],key.index[alphabet.index(message[x])])

Do:

new_message = message.replace(message[x],key[alphabet.index(message[x])])

Spowoduje to przejście wskaźnik litery i użyć go, aby uzyskać dostęp do listy key i uzyskać wartość w tym indeksie, aby zastąpić go oryginalną literą.

Edytuj: Lepszym sposobem, aby to zrobić, jest użycie dictionary i skonstruuj nowego strunu ISNTEAD, aby uniknąć podwójnego replace() na string

dic = {'a': '4', 'b': 'x', 'c': 'z' ...}
new_message = ''
for x in message:
    new_message += dic[x]
return new_message
2
Mohd 26 czerwiec 2017, 19:01