Using this program to take out spaces, punctuation, and make letters lower case...
def pre_process(s):
s= s.replace("'","")
s= s.replace('.','')
s= s.lower()
s= s.replace(" ","")
return s
How can I encrypt a message (s) so that the letters each shift by an amount equal to the corresponding letter in the alphabet? ex) 'm' shifted 5 becomes 'r' but 'w' shifted 5 becomes 'b'?
You have to do some ord and chr tricks to do what you want. Basically, these two functions return the integer representation of your letters, and outputs the corresponding letter of the integer representation, respectively.
def pre_process(s):
s= s.replace("'","")
s= s.replace('.','')
s= s.lower()
s= s.replace(" ","")
mystring = ""
for letter in s:
shift = 5
r = ord(letter)+shift
if (r > ord('z')):
r -= 26
mystring += (chr(r))
return mystring
This may be helpful to you...Just change the value of shifter in encrypt function to get the corresponding shift
def shift(char,shift_by):
val=ord(char) #gives ascii value of charecter
val+=shift_by
if(val>122):
val=97+(val-122-1)
return(chr(val))
def encrypt_string(str):
shifter=2 #change to value of shifter here
encrypted_string=""
for i in str :
if( (ord(i)>=97) and (ord(i)<=122) ):
i=shift(i,shifter)
encrypted_string+=i
return(encrypted_string)
Related
So Ive been working on a code to convert hexadecimal to ASCII then sort the letters with selection sort. But when I get a input such as HBbmYa, it outputs as B,H,Y,a,b,m. It should output as a,B,b,H,m,Y or a,B,b,H,m,y. Is there a way to solve this problem? Here is the code i have right now.
#ask for input
hex_str = input("Write hexadecimal string here without spaces: ")
#format the input so it doesn't have any spaces or commas for the code to work
hex_str = hex_str.replace("," , "")
hex_str = hex_str.replace(" " , "")
#convert input to ASCII
def hexToASCII(hexx):
# initialize the ASCII code string as empty.
asci = ""
for i in range(0, len(hexx), 2):
# extract two characters from hex string
part = hexx[i : i + 2]
# change it into base 16 and
# typecast as the character
ch = chr(int(part, 16))
# add this char to final ASCII string
asci += ch
return asci
#function call
ascii_output = hexToASCII(hex_str)
# print the ASCII string.
print("ASCII output is: {}".format(ascii_output))
def selectionSort(u):
sortedarry = []
def findSmallest(l):
x = l[0]
for i in l:
[ascii_output.lower() for ascii_output in u]
if i < x:
x = i
return l.index(x)
while len(u) > 0:
x = findSmallest(u)
sortedarry.append(u.pop(x))
return sortedarry
u = list(ascii_output)
sortedarry = selectionSort(u)
# print the sorted array
print("The sorted array is: {}".format(sortedarry))
In your findSmallest function, you could use a case insensitive comparison by lowercasing the two elements you compare:
def findSmallest(l):
x = l[0]
for i in l:
if i.lower() < x.lower():
x = i
return l.index(x)
Need to assign a value 1-26 to letters of the alphabet (i.e., a = 1, b = 2, etc.) and -1 to anything else in a sentence and then add up the values.
Currently have:
from string import ascii_lowercase
s = "Isn't it amazing?"
s = s.lower() #upper case version should have the same value as lower
letters = {letter: str(i) for i, letter in enumerate(ascii_lowercase, start=1)}
answer = [letters[char] for char in s if char in letters elif char not in letters -1]
for i in range(0, len(answer)):
answer[i] = int(answer[i])
sum(answer)
Desired return for sentence s is 158. Is there a way to use else in list comprehension?
Your else is in the wrong position. Also, ord is the usual way to translate a character to a number (subtract the value for 'a', adding one, to get 1-based numbers).
from string import ascii_lowercase
s = "Isn't it amazing?"
s = s.lower() #upper case version should have the same value as lower
vals = [ord(ch)-ord('a')+1 if ch in ascii_lowercase else -1 for ch in s ]
answer = sum(vals)
print(answer)
Dictionary provides a specific function for your use case: dict.get, from the documentation:
Return the value for key if key is in the dictionary, else default. If
default is not given, it defaults to None, so that this method never
raises a KeyError.
Code
from string import ascii_lowercase
s = "Isn't it amazing?"
s = s.lower() # upper case version should have the same value as lower
letters = {letter: i for i, letter in enumerate(ascii_lowercase, start=1)}
answer = [letters.get(char, -1) for char in s]
print(sum(answer))
Output
158
Also, notice that if plan to use the integer value of the enumerate you don't need to transform it into a string. If you insist in using a ternary operator, you could do it like this:
answer = [letters[char] if char in letters else -1 for char in s]
you can 1st convert the string into bytes and use the ascii byte value like below
s = "Isn't it amazing?"
s = s.lower()
sum([(b-96) if b>=97 and b<=122 else -1 for b in bytes(s, "ascii") ])
Considering char code of starting letter "a" as constant subtraction number:
sub_num = ord('a') - 1
answer = [ord(c) - sub_num if c.isalpha() else -1 for c in s]
print(sum(answer)) # 158
#variable defination#
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
valid=True
x=0
g=0
string=input("enter a string:")
#data validation#
for char in string:
if char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
valid=True
else:
valid=False
#finding the character#
if valid:
for char in string:
g+=1
for ele in upper:
if char!=ele:
x+=1
print(lower[x]+string[g::])
**I can't get it to work, it keeps iterating through the entire string without the condition ever being met. **
Since you are allowed to use lowercase and uppercase character inputs, you can create a dictionary mapping between them and use str.join with a list comprehension:
from string import ascii_lowercase, ascii_uppercase
d = dict(zip(ascii_uppercase, ascii_lowercase))
string = input("enter a string:")
res = ''.join([d.get(i, i) for i in string])
It's not clear whether this satisfies your "no in-built function" requirement.
I tried to minimize changes from your original code (But remember, it's obvious that other solutions are much better.)
#variable defination#
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
string=input("enter a string:")
#data validation#
valid = True
for char in string:
if char not in lower + upper:
valid=False
#finding the character#
if valid:
result = ""
for char in string:
if char in lower:
result += char
else:
# uppercase character
for i in range(len(upper)):
if char == upper[i]:
result += lower[i]
break
print(result)
You can create mapping(dictionary) between uppercase and lowercase alphabets such that upper_to_lower[uppercase] should give you lowercase. You may refer below implementation as reference though.
import string
def to_lower_case(word):
# construct auxilliary dictionary to avoid ord and chr built-in methods
upper_to_lower = {}
for index in range(len(string.ascii_uppercase)): # this is 26 we can use it as constant though
upper_to_lower[string.ascii_uppercase[index]] = string.ascii_lowercase[index]
result = ''
for alphabet in word:
if alphabet in string.ascii_uppercase:
result += upper_to_lower[alphabet]
else:
result += alphabet
return result
# sample input
In [5]: to_lower_case('ANJSNJN48982984aadkaka')
Out[5]: 'anjsnjn48982984aadkaka'
You can also write an index method to get the index of an uppercase character in the upper string:
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def index(char):
i = 0
for c in upper:
if char == c: return i
i += 1
Then you can convert your string to lowercase like this:
#data validation#
# ...
#finding the character#
s = ''
if valid:
for char in string:
if char in lower: s += char
else: s += lower[index(char)]
print(s)
A simple substitution cipher may be created by shifting or rotating the alphabet by a certain number of places. Using this system with a rotation of 5 gives us the following alphabets:
Plaintext alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Ciphertext alphabet: FGHIJKLMNOPQRSTUVWXYZABCDE
Any plain text message can be translated into the ciphertext by replacing each letter of the plain text alphabet with the letter in the ciphertext alphabet in the equivalent position. Spaces are left unchanged. For example, using the cipher above, the word DOG is enciphered as OBK.
Given a String and a rotation value, return the String translated into the ciphertext using the simple substitution method described above. You may assume that the text contains only spaces or capital letters and that the rotation value is always non-negative
function name: rotate_text
arguments:
text - input text to be encoded
n - an integer value specifying how many characters to rotate the text by
returns: a string containing the text rotated as described above
Testing
I am able to pass the test, but the result said I am u therenable to pass hidden or more test, Could someone help me?
def rotate_text(string1, int1):
loL = ['A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V',
'W','X','Y','Z']
strtoList = list(string1)
list1 = []
newStr = ""
if int1 == len(loL):
int1 = int1 % 26
for i in range(len(strtoList)):
if strtoList[i] in loL:
loLindex = loL.index(strtoList[i])
list1 += [loL[loLindex + int1]]
elif strtoList[i] == " ":
list1 += [" "]
for i in range(len(list1)):
newStr += list1[i]
return newStr
You need:
list1 += [loL[(loLindex + int1) % len(loL)]]
for whenever the cypher "loops back to the first letters".
And then
if int1 == len(loL):
int1 = int1 % 26
becomes irrelevant as well.
And BTW, you don't need to build a list and then make it a string. You can grow your string directly too...
After much frustration, I have made my first Caesar Decoder :)
But the problem now is to make the program circular...
For example if we want to shift doge by 1, no problem, it's ephf...
But what about xyz, and the shift was 4???
So programming pros help a first time novice aka newb out :P
Thanks...
import string
def main():
inString = raw_input("Please enter the word to be "
"translated: ")
key = int(raw_input("What is the key value? "))
toConv = [ord(i) for i in inString] #now want to shift it by key
toConv = [x+key for x in toConv]
#^can use map(lambda x:x+key, toConv)
result = ''.join(chr(i) for i in toConv)
print "This is the final result due to the shift", result
Here is Python code that I wrote to be easy to understand. Also, I think the classic Caesar cipher didn't define what to do with punctuation; I think the classic secret messages were unpunctuated and only contained letters. I wrote this to only handle the classic Roman alphabet and pass any other characters unchanged.
As a bonus, you can use this code with a shift of 13 to decode ROT13-encoded jokes.
def caesar_ch(ch, shift):
"""
Caesar cipher for one character. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
n = ord(ch)
if ord('a') <= n <= ord('z'):
n = n - ord('a')
n = (n + shift) % 26
n = n + ord('a')
return chr(n)
elif ord('A') <= n <= ord('Z'):
n = n - ord('A')
n = (n + shift) % 26
n = n + ord('A')
return chr(n)
else:
return ch
def caesar(s, shift):
"""
Caesar cipher for a string. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
return ''.join(caesar_ch(ch, shift) for ch in s)
if __name__ == "__main__":
assert caesar("doge", 1) == "ephf"
assert caesar("xyz", 4) == "bcd"
assert caesar("Veni, vidi, vici.", 13) == "Irav, ivqv, ivpv."
The part at the end is a "self-test" for the code. If you run this as a stand-alone program, it will test itself, and "assert" if a test fails.
If you have any questions about this code, just ask and I'll explain.
Just add the key to all the actual character codes, then if the added value is greater than z, modulo with character code of z and add it with the character code of a.
inString, key = "xyz", 4
toConv = [(ord(i) + key) for i in inString] #now want to shift it by key
toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv]
result = ''.join(chr(i) for i in toConv)
print result # cde
I'd recommend using string.translate().
So, we can do the following:
key = 1
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key])
And then we can use it as follows:
'doge'.translate(table) # Outputs 'ephf'
'Doge'.translate(table) # Outputs 'Ephf'
'xyz'.translate(table) # Outputs 'yza'
In particular, this doesn't change characters that are not ascii lowercase or uppercase characters, like numbers or spaces.
'3 2 1 a'.translate(table) # Outputs '3 2 1 b'
in general, to make something "wrap" you use the modulo function (% in Python) with the number you want to wrap, and the range you want it to wrap in. For example, if I wanted to print the numbers 1 through 10 a bajillion times, I would do:
i = 0
while 1:
print(i%10+1)
# I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1!
i += 1
In this case it's a little more difficult because you're using ord, which doesn't have a nice happy "range" of values. If you had done something like string.ascii_lowercase you could do...
import string
codex = string.ascii_lowercase
inString = "abcdxyz"
key = 3
outString = [codex[(codex.index(char)+key)%len(codex)] for char in inString]
However since you're using ord, we're kind of going from ord('A') == 65 to ord('z')==122, so a range of 0 -> 57 (e.g. range(58), with a constant of 65. In other words:
codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"
# every char for chr(65) -> chr(122)
codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing!
we can do this instead, but it WILL include the characters [\]^_`
inString, key = 'abcxyzABCXYZ', 4
toConv = [(ord(i)+key-65)%58 for i in inString]
result = ''.join(chr(i+65) for i in toConv)
print(result)
# "efgBCDEFG\\]^"
I know this is kind of an old topic, but I just happened to be working on it today. I found the answers in this thread useful, but they all seemed to use a decision to loop. I figured a way to accomplish the same goal just using the modulus(remainder) operator (%). This allows the number to stay within the range of a table and loop around. It also allows for easy decoding.
# advCeaser.py
# This program uses a ceaser cypher to encode and decode messages
import string
def main():
# Create a table to reference all upper, lower case, numbers and common punctuation.
table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890,.!?-#'
print 'This program accepts a message and a key to encode the message.'
print 'If the encoded message is entered with the negative value of the key'
print 'The message will be decoded!'
# Create accumulator to collect coded message
code =''
# Get input from user: Message and encode key
message = raw_input('Enter the message you would like to have encoded:')
key = input('Enter the encode or decode key: ')
# Loop through each character in the message
for ch in message:
# Find the index of the char in the table add the key value
# Then use the remainder function to stay within range of the table.
index = ((table.find(ch)+key)%len(table))
# Add a new character to the code using the index
code = code + table[index]
# Print out the final code
print code
main()
The encode and decode output look like this.
encode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:The zephyr blows from the east to the west!
Enter the encode or decode key: 10
croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
decode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
Enter the encode or decode key: -10
The zephyr blows from the east to the west!
Sorry if my formatting looks catywompus I literally found stackoverflow yesterday! Yes, I literally mean literally :)