How to encrypt lower case input - python-3.x

I am trying to create a simple encryption scheme. The scheme is working fine when I take input of the plain text in uppercase. But when I take input of the plain text in lowercase, it is not decrypted correctly.
Can anyone help me to find out the solution?
Here is my code:
def generateKey(string, key):
key = list(key)
st = list(string)
if len(string) == len(key):
return(key,st)
else:
x=len(string) -len(key)
if x>0:
for i in range(x):
key.append(key[i % len(key)])
else:
y=len(key)-len(string)
for j in range(y):
st.append("X")
return("" . join(key),"" . join(st))
def cipherText(string, key):
cipher_text = []
for i in range(len(string)):
if string[i]== " ":
x = ord(string[I])
i+=1
cipher_text.append(chr(x))
else:
abc = ord(string[i]) + ord(key[I])
x = (abc + 2) % 26
x += ord('A')
cipher_text.append(chr(x))
ci="" . join(cipher_text)
rev = ""
for i in ci:
rev = i + rev
return(rev)
def originalText(cipher_text, key):
orig_text = []
re_rev= ""
for i in cipher_text:
re_rev = i + re_rev
for i in range(len(re_rev)):
if re_rev[i]== " ":
x = ord(re_rev[I])
i+=1
orig_text.append(chr(x))
else:
abc = ord(re_rev[i]) - ord(key[i]) + 26
x = (abc - 2) % 26
x += ord('A')
orig_text.append(chr(x))
return("" . join(orig_text))
if __name__ == "__main__":
string = input("Enter Plain Text: ")
keyword = input("Enter Keyword: ")
key,stri = generateKey(string, keyword)
cipher_text = cipherText(stri,key)
print("Ciphertext :", cipher_text)
print("Original/Decrypted Text :",
originalText(cipher_text, key))

Related

I have to write a code for pattern recognition and replacing the pattern?

I have this problem statement where I have a column of patterns that were if the first four bytes have date it should replace those four bytes to ccyy and the rest to N and zeros to Z's
eg. 20190045689 -> CCYYZZNNNNN
if space we need to consider the space as well.
66-7830956 -> NN-NNNZNNN
def patternGeneration(string):
x = re.findall("[\s0-9a-zA-Z]", string)
n = len(x)
j = 0
r = re.compile("\A[^(19|20)]")
y = list(filter(r.match, x))
b = len(y)
for i in range(0, b):
if y[i] == "0":
y[i] = 0
elif y[i] == " ":
y[i] = " "
else:
y[i] = "n"
print(convert(y))
for i in range(0, n):
if x[i] == "0":
x[i] = 0
j = j + 1
elif x[i] == " ":
x[i] = " "
j = j + 1
else:
x[i] = "n"
print(convert(x))
str1 = input("enter the string\t")
patternGeneration(str1)
#convert to new format
def convert(string):
# check for year
head = string[:4]
tail = string[4:]
if head.isnumeric():
if 1900 <= int(head) <= 2099:
head = "CCYY"
new_string = head + tail
return "".join(["Z" if x == "0" else "N" if x.isnumeric() else x for x in str(new_string)])
sample = "20196705540"
print(convert(sample))
#"CCYYNNZNNNZ"
sample = "66-7830956"
print(convert(sample))
#"NN-NNNZNNN"

How to Change code from one .py file to another .py file

I need to add some code line in a .py file from another .py file
This is the file i want to add code lines:
Conversor_monedas
def menu():
x = int(input("Escoge tu moneda original, siendo:\n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n")) #(eeuu,europa,peru,brasil,uruguay,chile)
y = int(input("Escoge tu moneda convertida, siendo:\n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n"))
valorx = float(input("Cantidad a convertir: "))
if x == 1:
dolares(valorx,y)
if x == 2:
euros(valorx,y)
if x == 3:
soles(valorx,y)
if x == 4:
reales(valorx,y)
if x == 5:
pesos_uruguayos(valorx,y)
if x == 6:
pesos_chilenos(valorx,y)
def dolares(valorx,y):
if y == 2:
y = "euros"
valory = valorx*0.89
elif y == 3:
y = "soles"
valory = valorx*3.32
elif y == 4:
y = "reales"
valory = valorx*3.92
elif y == 5:
y = "pesos uruguayos"
valory = valorx*33.81
elif y == 6:
y = "pesos chilenos"
valory = valorx*680.50
print(valorx , "dólares equivalen a ", valory , y)
def euros(valorx,y):
if y == 1:
y = "dólares"
valory = valorx*1.12
elif y == 3:
y = "soles"
valory = valorx*3.73
elif y == 4:
y = "reales"
valory = valorx*4.41
elif y == 5:
y = "pesos uruguayos"
valory = valorx*37.97
elif y == 6:
y = "pesos chilenos"
valory = valorx*764.31
print(valorx , "euros equivalen a ", valory ,y)
menu()
...and so on with some other function like those two.
I want to add some other function with a new variable that defines another conversion variables from a different .py program that asks me what function I want to include in Conversor_monedas.
So, this may be way off from what you were thinking, but by entering conversion factors in a file, I believe you can achieve what you're trying to do. Here's a working sample.
#! python3
import csv
global ConvDict
def menu():
BuildCurrencyDict()
CurrencyList = []
FromCurrLit = "Escoge tu moneda original, siendo:"
ToCurrLit = "Escoge tu moneda original, siendo:"
# \n1.Dólares\n2.Euros\n3.Soles\n4.Reales\n5.Pesos uruguayos\n6.Pesos Chilenos\n")) #(eeuu,europa,peru,brasil,uruguay,chile
for i, Currency in enumerate(ConvDict):
FromCurrLit = FromCurrLit + "\n" + str(i+1) + ". " + Currency
ToCurrLit = ToCurrLit + "\n" + str(i+1) + ". " + Currency
CurrencyList.append(Currency)
FromCurrLit = FromCurrLit + "\n"
ToCurrLit = ToCurrLit + "\n"
x = int(input(FromCurrLit)) #(eeuu,europa,peru,brasil,uruguay,chile)
y = int(input(ToCurrLit))
valorx = float(input("Cantidad a convertir: "))
ConvFactor = float(ConvDict[CurrencyList[x-1]][CurrencyList[y-1]])
valory = valorx * ConvFactor
print(valorx , CurrencyList[x-1], "equivalen a", valory , CurrencyList[y-1])
def BuildCurrencyDict():
global ConvDict
CurrTypes= []
ConvDict = {}
# Put a matrix of currencies in CurrConv.txt
with open('CurrConv.txt') as csvfile:
data = csv.reader(csvfile, delimiter="\t")
for LineIn in data:
# user_info[name] = {'code': code, 'name': name, 'id': id}
for i, Item in enumerate(LineIn):
if data.line_num == 1:
if i == 0:
continue
else:
CurrTypes.append(Item)
else:
if i == 0:
FromCurr = Item
else:
if i == 1:
ConvDict[FromCurr] = {CurrTypes[i-1]:Item}
else:
ConvDict[FromCurr][CurrTypes[i-1]] = Item
# print(ConvDict["Euro"]["Dollar"]) # Testing Code
if __name__ == '__main__':
menu()
CurrConv.txt looks like this. I used tab delimited, but you could use semi-colons or some other delimiter if you wanted to. Line 1 starts with a tab. Then there are tabs between values. Simply add other currencies to the file and they will be added to your conversion prompts.
Euro Dollar Yen
Euro 1 1.12 124.53
Dollar 0.89 1 110.88
Yen 0.008 0.009 1

AttributeError: 'list' object has no attribute 'feature'

def tree_to_code(tree, feature_names):
tree_ = tree.estimators_
#print(tree_)
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
print("def tree({}):".format(", ".join(feature_names)))
symptoms_present = []
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print(name + " ?")
ans = input()
ans = ans.lower()
if ans == 'yes':
val = 1
else:
val = 0
if val <= threshold:
recurse(tree_.children_left[node], depth + 1)
else:
symptoms_present.append(name)
recurse(tree_.children_right[node], depth + 1)
else:
present_disease = print_disease(tree_.value[node])
print( "You may have " + present_disease )
red_cols = reduced_data.columns
symptoms_given = red_cols[reduced_data.loc[present_disease].values[0].nonzero()]
print("symptoms present " + str(list(symptoms_present)))
print("symptoms given " + str(list(symptoms_given)) )
confidence_level = (1.0*len(symptoms_present))/len(symptoms_given)
print("confidence level is " + str(confidence_level))
recurse(0, 1)
tree_to_code(clf,cols)
While changing decision tree code to random forest code,we got an attribute error at line 6 : for i in tree_.feature. Please help us to solve the error. It works using decision tree classifier but not using Random Forest Classifier .
List item

Caesar Cipher shift on new lines

I am having a problem with my code trying to do an advanced caesar cipher shift. I changed a certain letter to another, and then added a string to certain parts of a file before encoding, but am having problems doing the shifting now. This is my code:
import string
import sys
count = 1
cont_cipher = "Y"
#User inputs text
while cont_cipher == "Y":
if count == 1:
file = str(input("Enter input file:" ""))
k = str(input("Enter shift amount: "))
purpose = str(input("Encode (E) or Decode (D) ?: "))
#Steps to encode the message, replace words/letter then shift
if purpose == "E":
my_file = open(file, "r")
file_contents = my_file.read()
#change all "e"s to "zw"s
for letter in file_contents:
if letter == "e":
file_contents = file_contents.replace(letter, "zw")
#add "hokie" to beginning, middle, and end of each line
lines = file_contents.split('\n')
def middle_message(lines, position, word_to_insert):
lines = lines[:position] + word_to_insert + lines[position:]
return lines
new_lines = ["hokie" + middle_message(lines[x], len(lines[x])//2, "hokie") + "hokie" for x in range(len(lines))]
#math to do the actual encryption
def caesar(word, shifts):
word_list = list(new_lines)
result = []
s = 0
for c in word_list:
next_ord = ord(c) + s + 2
if next_ord > 122:
next_ord = 97
result.append(chr(next_ord))
s = (s + 1) % shifts
return "".join(result)
if __name__ == "__main__":
print(caesar(my_file, 5))
#close file and add to count
my_file.close()
count = count + 1
The error I am getting is:
TypeError: ord() expected a character, but string of length 58 found
I know that I need to split it into individual characters, but am not sure how to do this. I need to use the updated message and not the original file in this step...

Python 3 - How do I replace all letters in a sentence with their respective keys in a dictionary

So I'm creating a program that allows you to set each letter in the alphabet to another one using a dictionary. It then lets you input a sentence, which it then codes using the code you previously set. So far, I've completed (or I think I've completed) everything but the function that replaces the letters, because I have no idea what to do there. Any suggestions?
Here's the code:
import sys
def defineAlphabet():
alphabet = dict()
alphabet['a'] = input('a = ')
alphabet['b'] = input('b = ')
alphabet['c'] = input('c = ')
alphabet['d'] = input('d = ')
alphabet['e'] = input('e = ')
alphabet['f'] = input('f = ')
alphabet['g'] = input('g = ')
alphabet['h'] = input('h = ')
alphabet['i'] = input('i = ')
alphabet['j'] = input('j = ')
alphabet['k'] = input('k = ')
alphabet['l'] = input('l = ')
alphabet['m'] = input('m = ')
alphabet['n'] = input('n = ')
alphabet['o'] = input('o = ')
alphabet['p'] = input('p = ')
alphabet['q'] = input('q = ')
alphabet['r'] = input('r = ')
alphabet['s'] = input('s = ')
alphabet['t'] = input('t = ')
alphabet['u'] = input('u = ')
alphabet['v'] = input('v = ')
alphabet['w'] = input('w = ')
alphabet['x'] = input('x = ')
alphabet['y'] = input('y = ')
alphabet['z'] = input('z = ')
return alphabet
def codeSentence(sentence):
global translation
translation = 'WIP'
return translation
def menu():
print('''Would you like to:
a. Code a sentence
b. Set the code
c. Quit''')
userInput = input('//> ')
if userInput == 'a':
codeSentence(input('Enter Sentence: '))
print(translation)
menu()
if userInput == 'b':
defineAlphabet()
print('Defined!')
menu()
if userInput == 'c':
print('Goodbye!')
sys.exit(0)
else:
print('That is not an option.')
menu()
menu()
result = "some sentence".translate({ord(k): v for k, v in alphabet.items()})
See str.translate().

Resources