I had a coded text file that was coded by simple letter shifting. I have now gotten the information from it into two lists. In this format:
list_1 =['fjsir', 'vnjk', 'eioafnvjf', 'einbvfbj']
list_2 =[3,4,7,1]
The second list is by how many places in the alphabet should it move over. For eg. if index 0 in list one had 'fjsir'
and it's corresponding index in list_2
is 3 then it would decode to 'cfpeo'
. I'm not sure how I would match these in python.
Method #2 : Using defaultdict() + ascii_lowercase() + iter() In this we use defaultdict() to assign values to similar elements, ascii_lowercase() is used to get all lowercase all lowercased alphabets.
Python String isalpha() MethodThe isalpha() method returns True if all the characters are alphabet letters (a-z). Example of characters that are not alphabet letters: (space)! #%&? etc.
To shift elements to the left:
chr(ord(char) - n)
Which uses ord()
to get an integer representation of char
, and substracts n
from this number. It then uses chr()
to convert it back to a character.
The function could look like this:
def shift(s, n):
return ''.join(chr(ord(char) - n) for char in s)
Which can get called nicely with zip()
:
list_1 =['fjsir', 'vnjk', 'eioafnvjf', 'einbvfbj']
list_2 =[3,4,7,1]
for x, y in zip(list_1, list_2):
print(shift(x, y))
And gives back the decodings:
cgpfo
rjfg
^bhZ_goc_
dhmaueai
Additionally, if you only want decodings to only consist of letters from the English alphabet, you can use a modulus function %
instead:
def shift(s, n):
return ''.join(chr((ord(char) - 97 - n) % 26 + 97) for char in s)
Which gives back decodings with only letters:
cgpfo
rjfg
xbhtygocy
dhmaueai
Here is a simple solution:
alphabets = 'abcdefghijklmnopqrstuvwxyz'
list_1 = ['fjsir', 'vnjk', 'eioafnvjf', 'einbvfbj']
list_2 = [3,4,7,1]
final_list = []
for index,original_word in enumerate(list_1):
new_word = ''
for letter in original_word:
if letter in alphabets:
index_val = alphabets.index(letter) - list_2[index]
new_word += alphabets[index_val]
final_list.append(new_word)
print final_list
Output: ['cgpfo', 'rjfg', 'xbhtygocy', 'dhmaueai']
You can convert characters to number with ord()
and convert numbers to characters with chr()
. A shift function may look like:
def shift_string(inString, inOffset):
return "".join([chr(ord(x) + inOffset) for x in inString])
Accessing array elements from list is left to the reader. ;)
Note: This simple version will probably produce unwanted characters. You may simply use a modulo function to remain in the ASCII range.
def shift_string(inString, inOffset):
return "".join([chr(((ord(x) - ord(' ') + inOffset) % 95) + ord(' ')) for x in inString])
If your set of valid characters is more complex (e.g. letters), you should write a special function for the character transformation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With