Encryption with own Cipher Dictionary - python

Here is my code:
dictionary = {'A':'3',
'B':'u',
'C':'t',
'D':'5',
'E':'b',
'F':'6',
'G':'7',
'H':'8',
'I':'/',
'J':'9',
'K':'0',
'L':'-',
'M':'o',
'N':'i',
'O':';',
'P':'}',
'Q':'c',
'R':'n',
'S':'4',
'T':'m',
'U':'.',
'V':'y',
'W':'v',
'X':'r',
'Y':',',
'Z':'e',
}
print(dictionary)
inp = input(str("What do you want me to encode?").upper()).upper()
li = list(inp)
print(li)
for letter in inp:
pass
I want to ask how I could use this dictionary to encrypt any message that goes through the input. Like 'Hello my name is Jerry' would turn into: (Without Phrasing) '8b--; o, i3ob /4 9bnn,'.
Could someone please help me with this. Ive seen other questions like this being asked - but they use PyCrypto. I dont want to go through the hassle of installing it. Could someone please help me.
Thanks,
Jerry

You need to pass each character of the user input through the dictionary to get the cypher value out.
# removed the first .upper() here
inp = input(str("What do you want me to encode?")).upper()
li = list(inp)
print(li)
# create a list of letters passed through the dictionary
out = [dictionary[letter] for letter in inp]
# using ''.join makes the new list a single string
print(''.join(out))

You can use the str.translate method. The benefit here is that you only have to create the table once, so you can use the same table even if you have lots of strings to encrypt.
table = str.maketrans(dictionary) # create a translate table
inp = input("What do you want me to encode? ").upper()
res = inp.translate(table)
print(res)

Related

Deciphering script in Python issue

Cheers, I am looking for help with my small Python project. Problem says, that program has to be able to decipher "monoalphabetic substitute cipher", while we have complete database, which words will definetely (at least once) be ciphered.
I have tried to create such a database with words, that are ciphered:
lst_sample = []
n = int(input('Number of words in database: '))
for i in range(n):
x = input()
lst_sample.append(x)
Way, that I am trying to "decipher" is to observe words', let's say structure, where different letter I am assigning numbers based on their presence in word (e.g. feed = 0112, hood = 0112 are the same, because it is combination of three different letters in such a combination). I am using subprogram pattern() for it:
def pattern(word):
nextNum = 0
letternNums = {}
wordPattern = []
for letter in word:
if letter not in letterNums:
letternNums[letter] = str(nextNum)
nextNum += 1
wordPattern.append(letterNums[letter])
return ''.join(wordPattern)
Right after, I have made database of ciphered words:
lst_en = []
q = input('Insert ciphered words: ')
if q == '':
print(lst_en)
else:
lst_en.append(q)
With such a databases I could finally create process to deciphering.
for i in lst_en:
for q in lst_sample:
x = p
word = i
if pattern(x) == pattern(word):
print(x)
print(word)
print()
If words in database lst_sample have different letter length (e.g. food, car, yellow), there is no problem to assign decrypted words, even when they have the same length, I can sort them based on their different structure: (e.g. puff, sort).
The main problem, which I am not able to solve, comes, when word has the same length and structure (e.g. jane, word).
I have no idea how to solve this problem, while keeping such an script architecture as described above. Is there any way, how that could be solved using another if statement or anything similar? Is there any way, how to solve it with infortmation that words in lst_sample will for sure be in ciphered text?
Thanks for all help!

How do I check whether an input string has alphabets in another string in Python?

As the title says, how do I check whether an input string has alphabets in another string in Python?
The string specifies that only alphabets A to G ('ABCDEFG') can be used in the input string. However, my attempt did not get the results I want. Instead, input strings with alphabets in order such as 'ABC' and 'ABCD' work, while those not in order such as 'BADD' and 'EFEG' do not.
Please refer to my attempt below.
ID = 'ABCDEFG'
addcode=input('Enter new product code: ')
Code = []
if addcode in ID:
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
Ideally, as long as the input string contain letters from A to G, it should be appended to 'Code' regardless of the order. How do I modify my code so that I can get the results I want? Thank you.
You can use RegEx:
re.search('[a-zA-Z]', string)
You can try converting your input string (addcode) to a set and then see if it is a subset of ID. I am not converting ID into a set as it contains unique elements as per your code:
ID = 'ABCDEFG'
addcode = input('Enter new product code: ')
Code = []
if set(addcode).issubset(ID):
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
If you want to use a RegEx based approach, you can do this:
import re
pattern = re.compile("^[A-G]+$")
addcode = input('Enter new product code: ')
Code = []
if pattern.findall(addcode):
Code.append(addcode)
print(Code)
else:
print("Product code is invalid")
We are checking if the input string contains only characters between A-G here i.e A,B,C,D,E,F,G. If there is a match, we append the input string and print it.
String is immutable. You should check whether each letter of product code is present in the ID.
To achieve this you can use ID as tuple instead of single string.
ID = ('A','B','C','D','E','F','G')
addcode=input('Enter new product code: ')
Code = []
for l in range(0,len(addcode)):
if addcode[l] in ID:
Code.append(addcode[l])
else:
print("Product code is invalid")
print(Code)

How can I make strings automatically in Python 3.7?

Now, I'm learning Python and I want to make a dictionary, where the user can add words (in first step just the word, later definition).
word = input('Write a word here')
print('You added ' + word)
So, what I would like is the user can add more word, and the program save it to other string.
How can I do this?
Typically, this could be done in a while-loop where the loop-condition variable is updated upon user input:
continue_condition = True
words = []
while continue_condition:
word = input("Write a word here")
words.append(word)
continue_condition = input("Would you like to add another word? Then please type `Y`") == "Y"
If you want to populate a dictionary instead of a list, just adapt this code to your specific needs.
this will help to automate:
dict = {} # variable to store the key and value
def add(): # add function to add more word in our dictionary.
word = input('enter the word: ') # take the user input
dict[word] = word; # this will add the word to our dict for simplicity this is sample so we are using the same key and value.
if('y' == input('do you want to add more word (y/n): ')): # check if user want to add more word to dictionary.
add() # if yes the call function again ---recursion.
add() # call function for add word for first time.
print(dict) # print all the words in our dict.

How do you output a list out without quotes around strings?

I'm trying to set up a block to accept only inputs that are in a list but first it asks for the inputs in the input function but I can't seem to get rid of the quotes around the strings in the list. Here is some example code:
def Sinput(acceptable):
while True:
acceptable = [str(i) for i in acceptable]
a = input('Enter'+str(acceptable[:-1]).strip('[]')+' or '+str(acceptable[-1]+': '))
if a in acceptable:
return a
break
a = Sinput([ 1, 2.01, '\'cat\'', 'dog'])
print('you entred:', a)
The input asks: Enter'1', '2.01', "'cat'" or dog: I want it to ask: Enter 1, 2.01, 'cat' or dog:
Using .replace('\'', '') won't work because the input 'cat' would no longer display correctly
Thanks for any help, I've only been doing coding for about a week.
Use .join(...) which is the recommended way for joining an iterable of strings:
a = input('Enter'+ ' ,'.join(acceptable[:-1]) + ...)
# ^^^^^^^^^
P.S. I don't see why you need a break after that return statement.
I think this would do good for you:
a = input('Enter {} or {}'.format(' ,'.join(acceptable[:-1]), acceptable[-1]))

Python encrypt a string using an alternate alphabet

I'm unsure on how to make this work. I need to encrypt a string given a different alphabet.
def substitute(string, ciphertext):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
encrypted = []
list(alphabet)
list(ciphertext)
encrypted = ""
for x in string:
if x.isalpa():
encrypted.append(ciphertext[x])
else:
encrypted.append(x)
word = string.join(encrypted)
print(encrypted)
return encrypted
Try this out:
def substitute(string, ciphertext):
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") # list() returns a list,
ciphertext = list(ciphertext) # it doesn't change (mutate) the variable
encrypted = [] # Not sure why you were storing the empty string here,
# but strings cannot use the append() method.
for x in string:
if x.isalpha(): # Fixed a typo
# Here I think you want to use alphabet.index(x) instead of x.
encrypted.append(ciphertext[alphabet.index(x)])
else:
encrypted.append(x)
return "".join(encrypted) # Turning the list into a string
As the other commenter said, in the future please add examples of what you do and don't what your code to do.
I would suggest looking up the definition of mutability since that seems to be what you are struggling with.

Categories