Adrien
Adrien

Reputation: 27

Reverse alphabet

I’m trying to modify a piece of text to apply the following translation:

before: abcdefghijqlmnopqrstuvwxyz
after:  zyxwvutsrqponmlkjihgfedcba

That is, each a becomes a z; each b becomes a y; each c becomes a x; and so on.

My script :

myInput = input("Entrer une chaine de caracteres:\n\n")
myInputSansEspace = myInput.replace(" ", "")

myInputAsciiInverse = myInputSansEspace.replace("a","z").replace("b","y").replace("c","x").replace("d","w").replace("e","v").replace("f","u").replace("g","t").replace("h","s").replace("i","r").replace("j","q").replace("k","p").replace("l","o").replace("m","n").replace("n","m").replace("o","l").replace("p","k").replace("q","j").replace("r","i").replace("s","h").replace("t","g").replace("u","f").replace("v","e").replace("w","d").replace("x","c").replace("y","b").replace("z","a")

print(myInputAsciiInverse)

Unfortunately it doesn’t work. For example if I write:

i am noob

The return should be be:

rznmlly

Because i gets replaced by r; a by z; m by n; etc.

The result I get is:

boonmai

Upvotes: 1

Views: 20947

Answers (9)

Sam
Sam

Reputation: 1

This problem looks similar to Atbash which can be solved using arithmetic on the ASCII characters present within a string and using a conditional for adjusting the min and max boundaries for lower and uppercase input. e.g.

F(x) = min + (max - x)

Where min and max are your ASCII boundaries (96 and 123 for lowercase, 64 and 91 for uppercase) and x is the ASCII value of the character you are 'flipping'.

F('a')

F(97) = 96 + (123 - 97) = 122 ('z')

def Atbash(cipher):

output = ""
for i in range(0, len(cipher)):
    c = ord(cipher[i])
    if 96 <= c <= 123:
        c = 96 + (123-c)
    if 64 <= c <= 91:
        c = 64 + (91 - c)
    output = output + chr(c)
return output

print(Atbash("ciphEr this"))

print(Atbash("ciphEr this"))

xrksVi gsrh

Upvotes: 0

Prabhas
Prabhas

Reputation: 1

string=' abcdefghijklmnopqrstuvwxyz  '
print(''.join(string[-string.index(i)-1] for i in input().lower())) 
#replacing string with reverse letters in list comprehension and joining them

Or

[print(chr(219-ord(c))if'`'<c<'{'else c,end='')for c in input().lower()]
#ord('a') + ord('z') = 219 

Upvotes: -1

Karate_enthu
Karate_enthu

Reputation: 1

The following piece of code reverses the lowercase characters by ignoring the uppercase and other characters:

def solution(x): 
    i=0
    m=""
    while(i<len(x)):
        if(ord(x[i])<97 or ord(x[i])>122):
            m=m+(m.join(x[i]))  
        else:
            if(ord(x[i])<123):
                m=m+(m.join(chr(((ord(x[i])+(2*(109-ord(x[i]))+1))))))
        i=i+1 
    print(m)

If you run this code with solution("@Tsrh rh vmxibkg!vw g-.vcg"), then you will get:

@This is encrypt!ed t-.ext

Upvotes: 0

user14269371
user14269371

Reputation: 1

# p[10:36] -> alphabet(lowercase)
# p[35:9:-1] -> reverse alphabet
# p[:10]+p[36:62]+p[62:] -> Remove uppercase, numbers and special characters 

import string
p = string.printable
k = [(x,y) for x in p[10:36] for y in p[35:9:-1]][0::27]
def solution(x):
    r = []
    for i in x:
        for k1,k2 in k:
            if i in p[:10]+p[36:62]+p[62:]:
                pass
            elif i == k1:
                r.append(k2)
    print(''.join(r))
    
    solution("yeah! i can't believe lance lost his job at the colony!!")

output:

"bvzs! r xzm'g yvorvev ozmxv olhg srh qly zg gsv xlolmb!!"

Upvotes: 0

AChampion
AChampion

Reputation: 30268

Your approach has side effects, so does not do what you want.
Take your first replace:

'a...z'.replace('a', 'z') == 'z...z'

Now consider the last replace:

'z...z'.replace('z', 'a') == 'a...a'

Hence ending up with only half the alphabet.

You can simply replace all the replaces with reverse or slicing:

'abc..xyz'.reverse() == 'zyx..cba'
'abc..xyz'[::-1] == 'zyx..cba'

If you are trying to translate as a means of a cypher then you can use str.maketrans and str.translate, e.g.:

>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> trans = str.maketrans(alphabet, alphabet[::-1], ' ')
>>> noob = 'I am noob'
>>> noob.lower().translate(trans)
'rznmlly'

Note: alphabet is equivalent to string.ascii_lowercase

The above is largely equivalent to:

>>> import string
>>> trans_table = dict(zip(string.ascii_lowercase, string.ascii_lowercase[::-1]))
>>> ''.join(trans_table.get(c, c) for c in noob.lower() if c not in ' ')
'rznmlly'

Upvotes: 10

Tumbu John
Tumbu John

Reputation: 1

# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 11:46:50 2020

@author: Tumbu John
An encryption program "REVERSE ALPHABET"
"""  

Dictionary containing the value(new form each letter will be converted to)

code = {"a":"z", "b":"y", "c":"x" ,"d":"w" ,"e":"v", "f":"u", "g":"t", "h":"s", "i":"r","j":"q","k":"p","l":"o", "m":"n", "n":"m", "o":"l", "p":"k", "q":"j", "r":"i", "s":"h", "t":"g", "u":"f", "v":"e", "w":"d","x":"c", "y":"b", "z":"a"," ":" "}

plainText = input("Enter text to be encrypted: ")
plainText = plainText.lower() #Converts the input to lowecase letters for better management and error free program since python is case sensitive
encryptedText = ""

For loop to check for every character of the input to be converted to their respective values (encrypted text)

 for c in plainText:

This block is added to leave non-alpha in message prevent errors for input not in dict

if c in "abcdefghijklmnopqrstuvwxyz ":#checks if each character of plainText exist in 26 letters of alphabet
    encryptedText += code[c]
else: #if a character doesn't exist in the dictionary, do nothing to it
    encryptedText+=c

Encrypted text gets printed

print("This is the encrypted text: ",encryptedText)

OUTPUT

>>> enter text to be encrypted: abcdefghijklmnopqrstuvwxyz
>>> this is the encrypted text: zyxwvutsrqponmlkjihgfedbca

See a picture of this program : See a picture of this program

Tumbu Nkeng John | Tumbu John | Reverse Alphabet | Reverse alphabet encryption program | Encryption program in python | Python

Upvotes: 0

Huy Vo
Huy Vo

Reputation: 2500

You can use python's slice to reverse a string:

>>> my_string = "abcdefghijqlmnopqrstuvwxyz"
>>> my_reversed_string = my_string[::-1]
>>> my_reversed_string
'zyxwvutsrqponmlqjihgfedcba'

Edit: OK so the question is how to translate a string using a reversed alphabet. With this kind of problem the first that comes to my mind is building a dictionary to do the translating:

>>> alphabet = "abcdefghijklmnopqrstuvwxyz"
>>> reversed_alphabet = alphabet[::-1] # zyxwvutsrqponmlkjihgfedcba
>>> my_dict = dict(zip(alphabet, reversed_alphabet))
>>> my_str = "i am noob"
>>> translated_str = ''.join(my_dict[c] for c in my_str.replace(' ', ''))
>>> translated_sentence
'rznmlly'

Upvotes: 1

akuiper
akuiper

Reputation: 215047

Here is a functional way to accomplish the replacement:

s = "I am noob"

import string   
letters = string.ascii_lowercase

# construct a dictionary mapping from a letter to its dual opposite starting from the end
# of the alphabet table
rep_dict = dict(zip(letters, letters[::-1]))

# use the dictionary to replace the letters
''.join(map(rep_dict.get, s.replace(" ", "").lower()))
# 'rznmlly'

The problem with your code is that you are doing replace('a', 'z')....replace('z', 'a') so all the previously replaced characters get replaced back.

Upvotes: 4

JoryAnderson
JoryAnderson

Reputation: 103

Python has a string function called .reverse(), which can be called by

var = "abcdefghijklmnopqrstuvwxyz"
var = var.reverse()
print var


> zyxwvutsrqponmlkjihgfedbca

Upvotes: 1

Related Questions