How do I fix my message encryption/decryption program? - python

I'm making a program that takes user input and either encrypts it or decrypts it using my custom dictionary.
The encryption works just fine, but I'm having issues making the decryption process work. For example, when you encrypt the letter "a", the letter becomes the number "22". but if you try to decrypt the number "22", it outputs "hh" since my dictionary has the letter "h" set to "2" and "a" set to "22".
How do I fix this? I'm a high school student with not a lot of experience with Python and would love any feedback regarding my program.
#The dictionary i used for the translation is as follows: T=1 H=2 E=3 Q=4 U=5 I=6 C=7 K=8 B=9 R=10 O=11 W=12 N=13 F=14 X=15 J=16 M=17 P=18 S=19 V=20 L=21 A=22 Z=23 Y=24 D=25 G=26
#Encryption Function
def encrypt(text):
code = {' ': ' ', 'a': '22 ', 'b': '9 ', 'c': '7 ', 'd': '25 ', 'e': '3 ', 'f': '14 ', 'g': '26 ', 'h': '2 ', 'i': '6 ', 'j': '16 ', 'k': '8 ', 'l': '21 ', 'm': '17 ', 'n': '13 ', 'o': '11 ', 'p': '18 ', 'q': '4 ', 'r': '10 ', 's': '19 ', 't': '1 ', 'u': '5 ', 'v': '20 ', 'w': '12 ', 'x': '15 ', 'y': '24 ', 'z': '23 '}
encryption = ""
for x in text:
encryption += code[x.lower()]
return encryption
#Decryption Function
def decrypt(number):
code = {' ': ' ', '22': 'a', '9': 'b', '7': 'c', '25': 'd', '3': 'e', '14': 'f', '26': 'g', '2': 'h', '6': 'i', '16': 'j', '8': 'k', '21': 'l', '17': 'm', '13': 'n', '11': 'o', '18': 'p', '4': 'q', '10': 'r', '19': 's', '1': 't', '5': 'u', '20': 'v', '12': 'w', '15': 'x', '24': 'y', '23': 'z'}
decryption = ""
for y in number:
decryption += code[y]
return decryption
#Variable to loop user input if input isn't valid
Loop = 1
while Loop == 1:
#user input
Option = str.lower(input("Do you want to encrypt or decrypt a message?: "))
#encryption
if Option == "encrypt":
Encryption_Text = input("What is the message you would like to encrypt: ")
print(encrypt(Encryption_Text))
Loop = 0
#decryption
elif Option == "decrypt":
Decryption_Number = input("What is the message you would like to decrypt: ")
print(decrypt(Decryption_Number))
Loop = 0
#invalid user input
else:
print("please input a valid option...")
Loop = 1

Add a breakpoint before for y in number:, then debug, continue, you will find number 22 is spilted, like the following pic shows:
From VARIABLES in the left block, you can see y:2, so you'll get h and output is hh
In this project you can change decryption += code[y] into decryption = code[number]
[edit]
since you want to input more than one number, you can accept the numbers and using split(),
code changes are below:
for y in number.split():
decryption += code[y]+" "

i came up with this
# The dictionary i used for the translation is as follows: T=1 H=2 E=3 Q=4 U=5 I=6 C=7 K=8 B=9 R=10 O=11 W=12 N=13 F=14 X=15 J=16 M=17 P=18 S=19 V=20 L=21 A=22 Z=23 Y=24 D=25 G=26
# Encryption Function
def encrypt(text):
code = {' ': '-', 'a': '22 ', 'b': '9 ', 'c': '7 ', 'd': '25 ', 'e': '3 ', 'f': '14 ', 'g': '26 ', 'h': '2 ',
'i': '6 ', 'j': '16 ', 'k': '8 ', 'l': '21 ', 'm': '17 ', 'n': '13 ', 'o': '11 ', 'p': '18 ', 'q': '4 ',
'r': '10 ', 's': '19 ', 't': '1 ', 'u': '5 ', 'v': '20 ', 'w': '12 ', 'x': '15 ', 'y': '24 ', 'z': '23 '}
encryption = ""
for x in text:
encryption += code[x.lower()]
return encryption
# Decryption Function
def decrypt(number):
code = {" ":" ", '-': ' ', '22': 'a', '9': 'b', '7': 'c', '25': 'd', '3': 'e', '14': 'f', '26': 'g', '2': 'h',
'6': 'i', '16': 'j', '8': 'k', '21': 'l', '17': 'm', '13': 'n', '11': 'o', '18': 'p', '4': 'q', '10': 'r',
'19': 's', '1': 't', '5': 'u', '20': 'v', '12': 'w', '15': 'x', '24': 'y', '23': 'z'}
decryption = ""
numbers = number.split(" ")
del numbers[-1]
for y in numbers:
if "-" in y:
num = y.split("-")[1]
decryption += " " + code[num]
else:
decryption += code[y]
return decryption
# Variable to loop user input if input isn't valid
Loop = 1
while Loop == 1:
# user input
Option = str.lower(input("Do you want to encrypt or decrypt a message?: "))
# encryption
if Option == "1":
Encryption_Text = input("What is the message you would like to encrypt: ")
print(encrypt(Encryption_Text))
Loop = 0
# decryption
elif Option == "2":
Decryption_Number = input("What is the message you would like to decrypt: ")
print(decrypt(Decryption_Number))
Loop = 0
# invalid user input
else:
print("please input a valid option...")
Loop = 1
i have modified the decrypt method, after seeing the comment under the other answer

Related

convert python to dart

I want to know how I can write the following python code in dart.
encrypt = str.maketrans({'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5',
'f': '6', 'g': '7', 'h': '8', 'i': '9', 'j': 'A',
'k': 'B', 'l': 'C', 'm': 'D', 'n': 'E', 'o': 'F',
'p': 'F', 'q': 'H', 'r': 'I', 's': 'J', 't': 'K',
'u': 'L', 'v': 'M', 'w': 'N', 'x': 'O', 'y': 'P',
'z': 'Q', ' ': 'X'})
text = input('Enter Text: ')
text_lower = text.lower()
enc_text = text_lower.translate(encrypt)
print(enc_text)
From my understating, you are trying to encrypt a text and convert each letter into a new one. In dart there is no such method like maketrans, but you can use a normal key-value map for this purpose:
import 'dart:convert';
import 'dart:io';
main() {
Map<String, String> letterMap = {
'a': '1',
'b': '2',
'c': '3',
'd': '4',
'e': '5',
'f': '6',
'g': '7',
'h': '8',
'i': '9',
'j': 'A',
'k': 'B',
'l': 'C',
'm': 'D',
'n': 'E',
'o': 'F',
'p': 'F',
'q': 'H',
'r': 'I',
's': 'J',
't': 'K',
'u': 'L',
'v': 'M',
'w': 'N',
'x': 'O',
'y': 'P',
'z': 'Q',
' ': 'X'
};
print('Enter Text: ');
String text = stdin.readLineSync(encoding: utf8) ?? "";
text = text.toLowerCase();
String encodedText = "";
for (var letter in text.split('')) encodedText += letterMap[letter] ?? "";
print(encodedText);
}

use only part of the data premutation

import itertools
alphabet = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
"I": 9,
"J": 10,
"K": 11,
"L": 12,
"M": 13,
"N": 14,
"O": 15,
"P": 16,
"Q": 17,
"R": 18,
"S": 19,
"T": 20,
"U": 21,
"V": 22,
"W": 23,
"X": 24,
"Y": 25,
"Z": 26
}
def gen_combination_values(n):
comb_values = {}
for i in range(n + 1):
for product in itertools.product(alphabet.keys(), repeat=i):
prod = list(product)
prod.sort()
value = 0
comb = ""
for char in prod:
value += alphabet[char]
comb += char
try:
comb_values[value].add(comb)
except KeyError:
comb_values[value] = set()
comb_values[value].add(comb)
print(comb_values)
return comb_values
I have this script
and I would like to use only a part of the permutation how to do it?
I want the next part of the script to use only all results up to 10
{0: {''}, 1: {'A'}, 2: {'B', 'AA'}, 3: {'C', 'AB', 'BA'}, 4: {'BB' , 'AC', 'D', 'CA'}, 5: {'AD', 'BC', 'E', 'CB', 'DA'}, 6: {'F', 'CC', ' AE ',' DB ',' BD ',' EA '}, 7: {' CD ',' AF ',' G ',' EB ',' FA ',' BE ',' DC '}, 8: {'AG', 'CE', 'EC', 'H', 'BF', 'FB', 'DD', 'GA'}, 9: {'AH', 'DE', 'HA', ' BG ',' CF ',' ED ',' I ',' GB ',' FC '}, 10: {' EE ',' HB ',' DF ',' FD ',' IA ',' AI ' , 'J', 'BH', 'CG', 'GC'},
and the rest not to use
11: {'FE', 'BI', 'CH', 'AJ', 'JA', 'DG', 'GD', 'IB', 'HC', 'EF'}, 12: {'EG' , 'CI', 'IC', 'BJ', 'FF', 'DH', 'HD', 'JB', 'GE'}, 13: {'EH', 'HE', 'DI', ' CJ ',' FG ',' JC ',' ID ',' GF '}, 14: {' DJ ',' EI ',' IE ',' HF ',' JD ',' GG ',' FH ' }, 15: {'EJ', 'IF', 'GH', 'JE', 'FI', 'HG'}, 16: {'IG', 'JF', 'FJ', 'GI', ' HH '}, 17: {' JG ',' GJ ',' HI ',' IH '}, 18: {' JH ',' II ',' HJ '}, 19: {' IJ ',' JI ' }, 20: {'JJ'}}
how to achieve this? Basically here's the whole code I don't know what to do with all the attempts failed
I'm looking for only the first ten premutations to be used from the code
I suggest a re-write of your gen_combination_values() function. There are less cumbersome ways to build your dictionary (which I show in this code). You then need to construct a new dictionary to return which is based on your limit (which defaults to 10).
import itertools
ALPHABET = {k:i for i, k in enumerate('ABCDEFGHIJ', 1)}
def gen_combination_values(n, limit=10):
comb_values = {}
for i in range(n + 1):
for product in itertools.product(ALPHABET, repeat=i):
value = sum(ALPHABET[c] for c in product)
comb = ''.join(c for c in product)
comb_values.setdefault(value, set()).add(comb)
return {k:v for k, v in comb_values.items() if k <= limit}
print(gen_combination_values(2))
Output:
{0: {''}, 1: {'A'}, 2: {'B', 'AA'}, 3: {'C', 'BA', 'AB'}, 4: {'D', 'AC', 'BB', 'CA'}, 5: {'DA', 'E', 'AD', 'BC', 'CB'}, 6: {'CC', 'AE', 'EA', 'BD', 'DB', 'F'}, 7: {'AF', 'FA', 'CD', 'BE', 'G', 'EB', 'DC'}, 8: {'AG', 'GA', 'CE', 'EC', 'FB', 'DD', 'H', 'BF'}, 9: {'CF', 'FC', 'AH', 'BG', 'ED', 'DE', 'GB', 'HA', 'I'}, 10: {'DF', 'EE', 'BH', 'IA', 'CG', 'AI', 'HB', 'GC', 'J', 'FD'}}
There is a small error in your main code, but this should do what you want to do I think:
import itertools
alphabet = {
"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
"I": 9,
"J": 10
}
def gen_combination_values(n):
comb_values = {}
for i in range(n + 1):
for product in itertools.product(alphabet.keys(), repeat=i):
value = 0
comb = ""
for char in product:
value += alphabet[char]
comb += char
try:
comb_values[value].add(comb)
except KeyError:
comb_values[value] = set()
comb_values[value].add(comb)
print(comb_values)
return comb_values
def gematria(word):
result = 0
for char in word:
result += alphabet[char]
return result
if __name__ == '__main__':
values = gen_combination_values(2)
for i,(k,v) in enumerate(values.items()):
if k <= 10:
print(i)

How to compare XLS file to json file?

Hi I have a task to compare some XLS files to json files I have working code but the loop is comparing only first row from xls, does not go to the next one.
def verify_xlsx_file_content_against_json(json, xlsx_path):
found_configs_ct = 0
xlsx_reader = XLSXReader()
data_frame = xlsx_reader.read_xlsx(xlsx_path, "Configuration Set")
for config in json_definition:
items_compared = 0
for item in config["content"]["items"]:
for index, row in data_frame.iterrows():
if config["segAlias"] == row["Seg Alias"] and item["itemsOrder"] == row["Items Order"]:
found_configs_ct += 1
if index == 0:
def_platforms = config["platforms"]
platforms = ["gp", "ios", "win32", "fb", "amazon"]
for platform in platforms:
if platform in def_platforms:
assert_equal_values(row[convert_def_platform_to_excel_platform_name(platform)], "Y","{" + platform + "} should be True! and is not.")
else:
assert_equal_values(row[convert_def_platform_to_excel_platform_name(platform)], "N","{" + platform + "} should be False! and is not.")
name_from_definition = config["content"]["items"][0]["name"] # all items have the same name thus index 0 is sufficient
assert_equal_values(row["Name"], name_from_definition, "Content name is invalid")
Logger.LogInfo(str(item["identifier"]) + ' identifier')
Logger.LogInfo(str(row["Identifier"]) + ' Identifier')
Logger.LogInfo(str(item["itemsOrder"]) + ' itemsOrder')
Logger.LogInfo(str(row["Items Order"]) + ' Items Order')
Logger.LogInfo(str(item["dValue"]) + ' dValue')
Logger.LogInfo(str(row["D Value, $"]) + ' D Value, $')
Logger.LogInfo(str(row["Pack Image"]) + ' PackImage from row <<<<<<<<<<<<<<<')
Logger.LogInfo(str(item["packImage"]) + ' packImage second from item-<<<<<<<<')
assert_equal_values(str(item["identifier"]), str(row["Identifier"]), "Identifier is not match!")
assert_equal_values(str(item["itemsOrder"]), str(row["Items Order"]), "Items Order is not match!")
assert_equal_values(str(item["packImage"]), str(row["Pack Image"]), "packImage is not match!")
assert_equal_values(str(item["dValue"]), str(row["D Value, $"]),"dValue not match!")
# assert_equal_values(str(item["remarks"]), str(row["Remarks"]), "Remarks is not match!")
items_compared += 1
break
assert_equal_values(items_compared, len(
config["content"]["items"]), "number of items compared is less than actual items")
return False
logging.info("verification done. ---no problems detected--")
return True # if code got here, no errors on the way, return True
what I get here is
NFO:root:[2020-02-14 09:33:24.543957] 0 identifier
INFO:root:[2020-02-14 09:33:24.543957] -1 Identifier
INFO:root:[2020-02-14 09:33:24.543957] 1 itemsOrder
INFO:root:[2020-02-14 09:33:24.543957] 1 Items Order
INFO:root:[2020-02-14 09:33:24.543957] 1.99 dValue
INFO:root:[2020-02-14 09:33:24.543957] 1.99 D Value, $
INFO:root:[2020-02-14 09:33:24.544953] 1 identifier
INFO:root:[2020-02-14 09:33:24.544953] -1 Identifier
INFO:root:[2020-02-14 09:33:24.544953] 2 itemsOrder
INFO:root:[2020-02-14 09:33:24.544953] 1 Items Order
INFO:root:[2020-02-14 09:33:24.544953] 2.99 dValue
INFO:root:[2020-02-14 09:33:24.544953] 1.99 D Value,
INFO:root:[2020-02-14 09:33:24.544953] 2 identifier
INFO:root:[2020-02-14 09:33:24.545949] -1 Identifier
So -1 Identifier is always -1 and should change incrementally (0,1,2... ) like in json file.
How to change this loop to make this code work? and later to assert those files json vs xls
What I did
df = pd.read_excel("download1.xlsx") #xlsx to json
json_from_excel = df.to_json() #json string
print(type(json_from_excel))
print(json_from_excel)
final_dictionary = json.loads(json_from_excel) #dict
print(type(final_dictionary))
print(final_dictionary)
with open('basic.json', 'r') as jason_file:
data = json.loads(jason_file.read())
for item in data:
print(type(item))
and the result is
<class 'str'>
{"Name":{"0":"default_config","1":"default_config","2":"default_config","3":"default_config","4":"default_config","5":"gems1","6":"gems1","7":"gems1","8":"gems1","9":"gems1","10":"gems2","11":"gems2","12":"gems2","13":"gems2","14":"gems2","15":"gems3","16":"gems3","17":"gems3","18":"gems3","19":"gems3"},"Identifier":{"0":11294,"1":11294,"2":11294,"3":11294,"4":11294,"5":11295,"6":11295,"7":11295,"8":11295,"9":11295,"10":11296,"11":11296,"12":11296,"13":11296,"14":11296,"15":11297,"16":11297,"17":11297,"18":11297,"19":11297},"Segment Alias":{"0":"default","1":"default","2":"default","3":"default","4":"default","5":"rhinoQA_1","6":"rhinoQA_1","7":"rhinoQA_1","8":"rhinoQA_1","9":"rhinoQA_1","10":"rhinoQA_2","11":"rhinoQA_2","12":"rhinoQA_2","13":"rhinoQA_2","14":"rhinoQA_2","15":"rhinoQA_3","16":"rhinoQA_3","17":"rhinoQA_3","18":"rhinoQA_3","19":"rhinoQA_3"},"Segment ID":{"0":-1,"1":-1,"2":-1,"3":-1,"4":-1,"5":95365,"6":95365,"7":95365,"8":95365,"9":95365,"10":95366,"11":95366,"12":95366,"13":95366,"14":95366,"15":95367,"16":95367,"17":95367,"18":95367,"19":95367},"GP":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"iOS":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"Y","6":"Y","7":"Y","8":"Y","9":"Y","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"FB":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"Y","11":"Y","12":"Y","13":"Y","14":"Y","15":"N","16":"N","17":"N","18":"N","19":"N"},"Amazon":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"Y","16":"Y","17":"Y","18":"Y","19":"Y"},"Win32":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"Remarks":{"0":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","1":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","2":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","3":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","4":"default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform","5":"*inserted_by_automated_test*","6":"*inserted_by_automated_test*","7":"*inserted_by_automated_test*","8":"*inserted_by_automated_test*","9":"*inserted_by_automated_test*","10":"x1","11":"x1","12":"x1","13":"x1","14":"x1","15":"x3","16":"x3","17":"x3","18":"x3","19":"x3"},"Pack Name":{"0":"test_bingo","1":"test_bingo","2":"test_bingo","3":"test_bingo","4":"test_bingo","5":"test_bingo","6":"test_bingo","7":"test_bingo","8":"test_bingo","9":"test_bingo","10":"test_bingo","11":"test_bingo","12":"test_bingo","13":"test_bingo","14":"test_bingo","15":"test_bingo","16":"test_bingo","17":"test_bingo","18":"test_bingo","19":"test_bingo"},"SKU":{"0":"gems_99","1":"gems_99","2":"gems_99","3":"gems_99","4":"gems_99","5":"gems_99","6":"gems_99","7":"gems_99","8":"gems_99","9":"gems_99","10":"gems_99","11":"gems_99","12":"gems_99","13":"gems_99","14":"gems_99","15":"gems_99","16":"gems_99","17":"gems_99","18":"gems_99","19":"gems_99"},"Sold Item":{"0":"Gems","1":"Gems","2":"Gems","3":"Gems","4":"Gems","5":"Gems","6":"Gems","7":"Gems","8":"Gems","9":"Gems","10":"Gems","11":"Gems","12":"Gems","13":"Gems","14":"Gems","15":"Gems","16":"Gems","17":"Gems","18":"Gems","19":"Gems"},"Items Order":{"0":1,"1":2,"2":3,"3":4,"4":5,"5":1,"6":2,"7":3,"8":4,"9":5,"10":1,"11":2,"12":3,"13":4,"14":5,"15":1,"16":2,"17":3,"18":4,"19":5},"Dollar Value, $":{"0":1.99,"1":2.99,"2":3.99,"3":4.99,"4":5.99,"5":1.99,"6":2.99,"7":3.99,"8":4.99,"9":5.99,"10":1.99,"11":11.99,"12":13.99,"13":14.99,"14":15.99,"15":1.99,"16":2.99,"17":3.99,"18":4.99,"19":5.99},"Item Quantity":{"0":5,"1":15,"2":25,"3":35,"4":45,"5":5,"6":15,"7":25,"8":55,"9":65,"10":5,"11":15,"12":45,"13":55,"14":75,"15":5,"16":15,"17":55,"18":95,"19":85},"Is Best":{"0":"Y","1":"Y","2":"Y","3":"Y","4":"Y","5":"Y","6":"Y","7":"Y","8":"Y","9":"Y","10":"Y","11":"Y","12":"Y","13":"Y","14":"Y","15":"Y","16":"Y","17":"Y","18":"Y","19":"Y"},"Is Popular":{"0":"N","1":"N","2":"N","3":"N","4":"N","5":"N","6":"N","7":"N","8":"N","9":"N","10":"N","11":"N","12":"N","13":"N","14":"N","15":"N","16":"N","17":"N","18":"N","19":"N"},"Footer Type":{"0":1,"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1,"11":1,"12":1,"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1},"Footer Text":{"0":"test_text","1":"test_text","2":"test_text","3":"test_text","4":"test_text","5":"test_text","6":"test_text","7":"test_text","8":"test_text","9":"test_text","10":"test_text","11":"test_text","12":"test_text","13":"test_text","14":"test_text","15":"test_text","16":"test_text","17":"test_text","18":"test_text","19":"test_text"},"Pack Image":{"0":"gems_1.png","1":"gems_2.png","2":"gems_3.png","3":"gems_4.png","4":"gems_5.png","5":"gems_1.png","6":"gems_2.png","7":"gems_3.png","8":"gems_4.png","9":"gems_5.png","10":"gems_1.png","11":"gems_2.png","12":"gems_3.png","13":"gems_4.png","14":"gems_5.png","15":"gems_1.png","16":"gems_2.png","17":"gems_3.png","18":"gems_4.png","19":"gems_5.png"}}
<class 'dict'>
{'Name': {'0': 'default_config', '1': 'default_config', '2': 'default_config', '3': 'default_config', '4': 'default_config', '5': 'gems1', '6': 'gems1', '7': 'gems1', '8': 'gems1', '9': 'gems1', '10': 'gems2', '11': 'gems2', '12': 'gems2', '13': 'gems2', '14': 'gems2', '15': 'gems3', '16': 'gems3', '17': 'gems3', '18': 'gems3', '19': 'gems3'}, 'Identifier': {'0': 11294, '1': 11294, '2': 11294, '3': 11294, '4': 11294, '5': 11295, '6': 11295, '7': 11295, '8': 11295, '9': 11295, '10': 11296, '11': 11296, '12': 11296, '13': 11296, '14': 11296, '15': 11297, '16': 11297, '17': 11297, '18': 11297, '19': 11297}, 'Segment Alias': {'0': 'default', '1': 'default', '2': 'default', '3': 'default', '4': 'default', '5': 'rhinoQA_1', '6': 'rhinoQA_1', '7': 'rhinoQA_1', '8': 'rhinoQA_1', '9': 'rhinoQA_1', '10': 'rhinoQA_2', '11': 'rhinoQA_2', '12': 'rhinoQA_2', '13': 'rhinoQA_2', '14': 'rhinoQA_2', '15': 'rhinoQA_3', '16': 'rhinoQA_3', '17': 'rhinoQA_3', '18': 'rhinoQA_3', '19': 'rhinoQA_3'}, 'Segment ID': {'0': -1, '1': -1, '2': -1, '3': -1, '4': -1, '5': 95365, '6': 95365, '7': 95365, '8': 95365, '9': 95365, '10': 95366, '11': 95366, '12': 95366, '13': 95366, '14': 95366, '15': 95367, '16': 95367, '17': 95367, '18': 95367, '19': 95367}, 'GP': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'iOS': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'Y', '6': 'Y', '7': 'Y', '8': 'Y', '9': 'Y', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'FB': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'Y', '11': 'Y', '12': 'Y', '13': 'Y', '14': 'Y', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Amazon': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'Y', '16': 'Y', '17': 'Y', '18': 'Y', '19': 'Y'}, 'Win32': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Remarks': {'0': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '1': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '2': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '3': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '4': 'default;A.request cfa for test user and any non existing platform to get default B. request user 520000000101987 (has segment in hbi redis,but not in config), any platform', '5': '*inserted_by_automated_test*', '6': '*inserted_by_automated_test*', '7': '*inserted_by_automated_test*', '8': '*inserted_by_automated_test*', '9': '*inserted_by_automated_test*', '10': 'x1', '11': 'x1', '12': 'x1', '13': 'x1', '14': 'x1', '15': 'x3', '16': 'x3', '17': 'x3', '18': 'x3', '19': 'x3'}, 'Pack Name': {'0': 'test_bingo', '1': 'test_bingo', '2': 'test_bingo', '3': 'test_bingo', '4': 'test_bingo', '5': 'test_bingo', '6': 'test_bingo', '7': 'test_bingo', '8': 'test_bingo', '9': 'test_bingo', '10': 'test_bingo', '11': 'test_bingo', '12': 'test_bingo', '13': 'test_bingo', '14': 'test_bingo', '15': 'test_bingo', '16': 'test_bingo', '17': 'test_bingo', '18': 'test_bingo', '19': 'test_bingo'}, 'SKU': {'0': 'gems_99', '1': 'gems_99', '2': 'gems_99', '3': 'gems_99', '4': 'gems_99', '5': 'gems_99', '6': 'gems_99', '7': 'gems_99', '8': 'gems_99', '9': 'gems_99', '10': 'gems_99', '11': 'gems_99', '12': 'gems_99', '13': 'gems_99', '14': 'gems_99', '15': 'gems_99', '16': 'gems_99', '17': 'gems_99', '18': 'gems_99', '19': 'gems_99'}, 'Sold Item': {'0': 'Gems', '1': 'Gems', '2': 'Gems', '3': 'Gems', '4': 'Gems', '5': 'Gems', '6': 'Gems', '7': 'Gems', '8': 'Gems', '9': 'Gems', '10': 'Gems', '11': 'Gems', '12': 'Gems', '13': 'Gems', '14': 'Gems', '15': 'Gems', '16': 'Gems', '17': 'Gems', '18': 'Gems', '19': 'Gems'}, 'Items Order': {'0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 1, '6': 2, '7': 3, '8': 4, '9': 5, '10': 1, '11': 2, '12': 3, '13': 4, '14': 5, '15': 1, '16': 2, '17': 3, '18': 4, '19': 5}, 'Dollar Value, $': {'0': 1.99, '1': 2.99, '2': 3.99, '3': 4.99, '4': 5.99, '5': 1.99, '6': 2.99, '7': 3.99, '8': 4.99, '9': 5.99, '10': 1.99, '11': 11.99, '12': 13.99, '13': 14.99, '14': 15.99, '15': 1.99, '16': 2.99, '17': 3.99, '18': 4.99, '19': 5.99}, 'Item Quantity': {'0': 5, '1': 15, '2': 25, '3': 35, '4': 45, '5': 5, '6': 15, '7': 25, '8': 55, '9': 65, '10': 5, '11': 15, '12': 45, '13': 55, '14': 75, '15': 5, '16': 15, '17': 55, '18': 95, '19': 85}, 'Is Best': {'0': 'Y', '1': 'Y', '2': 'Y', '3': 'Y', '4': 'Y', '5': 'Y', '6': 'Y', '7': 'Y', '8': 'Y', '9': 'Y', '10': 'Y', '11': 'Y', '12': 'Y', '13': 'Y', '14': 'Y', '15': 'Y', '16': 'Y', '17': 'Y', '18': 'Y', '19': 'Y'}, 'Is Popular': {'0': 'N', '1': 'N', '2': 'N', '3': 'N', '4': 'N', '5': 'N', '6': 'N', '7': 'N', '8': 'N', '9': 'N', '10': 'N', '11': 'N', '12': 'N', '13': 'N', '14': 'N', '15': 'N', '16': 'N', '17': 'N', '18': 'N', '19': 'N'}, 'Footer Type': {'0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1, '10': 1, '11': 1, '12': 1, '13': 1, '14': 1, '15': 1, '16': 1, '17': 1, '18': 1, '19': 1}, 'Footer Text': {'0': 'test_text', '1': 'test_text', '2': 'test_text', '3': 'test_text', '4': 'test_text', '5': 'test_text', '6': 'test_text', '7': 'test_text', '8': 'test_text', '9': 'test_text', '10': 'test_text', '11': 'test_text', '12': 'test_text', '13': 'test_text', '14': 'test_text', '15': 'test_text', '16': 'test_text', '17': 'test_text', '18': 'test_text', '19': 'test_text'}, 'Pack Image': {'0': 'gems_1.png', '1': 'gems_2.png', '2': 'gems_3.png', '3': 'gems_4.png', '4': 'gems_5.png', '5': 'gems_1.png', '6': 'gems_2.png', '7': 'gems_3.png', '8': 'gems_4.png', '9': 'gems_5.png', '10': 'gems_1.png', '11': 'gems_2.png', '12': 'gems_3.png', '13': 'gems_4.png', '14': 'gems_5.png', '15': 'gems_1.png', '16': 'gems_2.png', '17': 'gems_3.png', '18': 'gems_4.png', '19': 'gems_5.png'}}
{'id': 0, 'segmentAlias': 'default', 'userIds': [-1], 'platforms': ['gp'], 'content': {'items': [{'name': 'default_config', 'identifier': 0, 'itemsOrder': 1, 'dollarValue': 1.99, 'remarks': 'default!', 'itemsQuantity': 5, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_1.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 1, 'itemsOrder': 2, 'dollarValue': 2.99, 'remarks': 'default!', 'itemsQuantity': 15, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_2.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 2, 'itemsOrder': 3, 'dollarValue': 3.99, 'remarks': 'default!', 'itemsQuantity': 25, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_3.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 3, 'itemsOrder': 4, 'dollarValue': 4.99, 'remarks': 'default!', 'itemsQuantity': 35, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_4.png', 'SKU': 'gems_99'}, {'name': 'default_config', 'identifier': 4, 'itemsOrder': 5, 'dollarValue': 5.99, 'remarks': 'default!', 'itemsQuantity': 45, 'is_best': 'Y', 'is_popular': 'N', 'packName': 'test_bingo', 'footerType': 1, 'footerText': 'test_text', 'soldItem': 'Gems', 'packImage': 'gems_5.png', 'SKU': 'gems_99'}]}}
<class 'dict'>
{'id': 1, 'segmentAlias': 's1', 'userIds': [-1], 'platforms': ['ios'], 'content': {'items': [{'name': 'gems1', 'identifier': 0, 'itemsOrder': 1, 'dollarValue': 1.99, 'remarks': 'x', 'itemsQuantity': 5,
I cannot compare those dicts
You will need to read the excel file and convert it to json with pandas. Also check in which format is your json file when converting from pandas. Maybe you need to change the orientation.
df = pd.read_excel(xlsx, sheet_name=sheet)
json_from_excel = df.to_json(orient='records')
Next you will need to order your json data here is an example function.
def ordered(obj):
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in obj.items())
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj
And finally you can make the compare.
if ordered(json_from_excel) == ordered(json_data):
#do something

File Encryption and Decryption using a given key

I have a problem for school and I can't seem to figure it out. Basically, i'm in an intro to object oriented programming class, so I only need to complete this as basic as possible without using anything fancy that I haven't learned yet. Currently learning about dictionaries and sets, I need to use a dictionary that has a code written in it to encrypt a document that has a long string on one line.
So I need one part to read the dictionary and open the text file containing the string.
"The course Introduction to Object Oriented Programming uses the Python programming language."
I need to then use the code from this dictionary to encrypt it and write the encrypted version of the string to another text file called encrypt.txt.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
This is the code I have so far. Any help would be greatly appreciated and an explanation in layman's terms would also be greatly appreciated.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#strip the newline
#dtext = dtext.rstrip('\n')
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#set accumulator value
count = 0
#create a for loop to read each separate character
for line in dtext:
wordList = line.split()
print(dtext, CODE[dtext])
count += 1
main()
You need to encrypt character by character and you need to take the result and build it back into a string. str.join turns a sequence of characters into a string and a generator can be written to encrypt each character... put them together and you have your solution.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#strip the newline
#dtext = dtext.rstrip('\n')
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#set accumulator value
#create a for loop to read each separate character
for line in dtext:
# encrypt character by character then join to a string
encrypted = ''.join(CODE.get(c, c) for c in line)
print(repr(line), repr(encrypted))
etext.write(encrypted)
etext.close()
main()
Strings are immutable. That means you cannot edit them after creation, in direct contrast to arrays. You will have to build a new string in order to encrypt your text. You will also likely need to do this one character at a time. Since you have the text of the file in dtext as a string, you can loop through the chars in the original string like so:
for i in range (0, len(dtext)):
# add new character to string
(I'm breaking this apart so you cannot just copy and paste)
You must create a new string to put the encrypted text in outside of that for loop.
enc = ""
In order to encrypt the value by making a substitution you can add character one at a time to the encrypted string in that for loop if they are in the dictionary you defined. Something to the effect of
if (dtext[i] in CODE.keys()):
enc += CODE[dtext[i]]
Then write the new string to a file and you're good to go.
A dictionary in python is effectively an array that is indexable by a key. This key maps to a given value just like an array index maps to some value. See https://www.tutorialspoint.com/python/python_dictionary.htm for more details.
tdelaney's answer was correct, but I took it and made it a more simpler version. I changed it a bit. This is what I did:
Instead of joining to an empty string, I just removed that part completely. I just iterated over the entire string character by character and then as tdelaney did, used the get method to use the key in the code dictionary.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '#', 'i': '2',
'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
'#': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
'%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
'*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
"'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
'{': '[', '[': '{', '}': ']', ']': '}'}
def main():
#Open the file you want to encrypt.
infile = str(input('Enter the name of the input file: '))
#read its contents
dtext = open(infile, 'r')
#read the line from the file
dtext = dtext.readlines()
#call the encryptText function
encryptText(dtext)
def encryptText(dtext):
#enter the name of the file to write to
outfile = str(input('Enter the name of the output file: '))
#open the file to send encrypted text to
etext = open(outfile, 'w')
#create a for loop to read each separate character
for line in dtext:
# encrypt character by character then join to a string
for c in line:
encrypted = (CODE.get(c, c))
etext.write(encrypted)
#close the file
etext.close()
main()

Why my code prints others characters? cipher

I want print only letters but it's prints special characters of ASCII. My code:
import string
def caesar(shift):
alphabet = string.ascii_lowercase + string.ascii_uppercase
dict={}
emptylist=[]
int(shift)
for x in alphabet:
emptylist.append(x)
code = ""
for letters in emptylist:
code = chr(ord(letters) + shift)
dict[letters]=code
return dict
caesar(12)
My output:
'm': 'y', 'l': 'x', 'o': '{', 'n': 'z', 'q': '}', 'p': '|', 's': '\x7f', 'r': '~', 'u': '\x81', 't': '\x80', 'w': '\x83', 'v': '\x82', 'y': '\x85', 'x': '\x84', 'z': '\x86'
Correct output:
'm': 'y', 'l': 'x', 'o': 'a', 'n': 'z', 'q': 'c', 'p': 'b', 's': 'e', 'r': 'd', 'u': 'g', 't': 'f', 'w': 'i', 'v': 'h', 'y': 'k', 'x': 'j', 'z': 'l'
Using ord() and changing the character code won't restrict the resulting character to your dictionary.
I'd just find the index of the letter in your dictionary, shift it, and use the modulo operator:
import string
def caesar(shift):
alphabet = string.ascii_uppercase # <- Change it back to what you had before
# and see what will happen.
mapping = {}
for letter in alphabet:
index = alphabet.index(letter)
mapping[letter] = alphabet[(index + shift) % len(alphabet)]
return mapping
Test (dictionaries don't preserve order, so it's pretty hard to read):
>>> caesar(12)
{'A': 'M', 'C': 'O', 'B': 'N', 'E': 'Q', 'D': 'P', 'G': 'S', 'F': 'R', 'I': 'U', 'H': 'T', 'K': 'W', 'J': 'V', 'M': 'Y', 'L': 'X', 'O': 'A', 'N': 'Z', 'Q': 'C', 'P': 'B', 'S': 'E', 'R': 'D', 'U': 'G', 'T': 'F', 'W': 'I', 'V': 'H', 'Y': 'K', 'X': 'J', 'Z': 'L'}
Let's look at one error in particular: o: '{'.
Notice that ord('o') is 111, so let's look at the chr of integers in the range(111,130):
Starting at o, shifting by 12, takes you to the { character:
In [75]: ' '.join([chr(x) for x in range(111,130)])
Out[75]: 'o p q r s t u v w x y z { | } ~ \x7f \x80 \x81'
^ 1 2 3 4 5 6 7 8 9 ...12
So the reason why you are getting incorrect output is because your formula
code = chr(ord(letters) + shift)
isn't taking into account what happens if the shift bounces you out of the ords associated with a-z or A-Z. (Note that the ord ranges for a-z and A-Z are not contiguous either!)
Here is a hint on how to fix:
In [82]: alphabet = string.ascii_lowercase + string.ascii_uppercase
In [83]: alphabet.index('o')
Out[83]: 14
In [84]: alphabet[alphabet.index('o')+12]
Out[84]: 'A'
but
In [85]: alphabet[alphabet.index('O')+12]
results in IndexError: string index out of range. That's because len(alphabet) is 52, and
In [91]: alphabet.index('O')+12
Out[91]: 52
Somehow we need 52 to wrap back around to 0. You can do that with the % modulo operator:
In [92]: 52 % 52
Out[92]: 0

Categories

Resources