[Tutor] Python challenge and decryption
Prasad, Ramit
ramit.prasad at jpmorgan.com
Mon Dec 19 21:46:12 CET 2011
Hi list!
<snip>
My Python version is 2.7.1 and my OS is Linux Mint 11.
My code is this one:
def decrypt(cypheredText, shiftedCypherNumber):
'''
This function will take two arguments. The first is the cyphered text, the second
is the number of characters we need to shift the text so we can decrypt it.
This is a Caesar cypher.
'''
crypticText = list(cypheredText)
for letter in crypticText:
asciiValue = ord(letter)
asciiValue += shiftedCypherNumber
newLetter = chr(asciiValue)
print newLetter
This solves the riddle, however some characters are not correctly decyphered (a is coming back as {...) and prints the solution like this:
r
e
c
o
m
m
<snip>
- How can I make this "Human readable"? ... Print the letters in just one (or more) lines and maybe replace the " for spaces (This one I suppose it could/should be done with whitespaces() or just making a loop to check and change those for ' '.)
Thanks for your time!
--
Joaquim Santos
http://js-vfx.com
linkedin
=============================================
Remove the print in the function.
Add each character to a list (char_list) after
you are have gotten newLetter:
return ''.join( char_list )
def decrypt(cypheredText, shiftedCypherNumber):
'''
This function will take two arguments. The first is the cyphered text, the second
is the number of characters we need to shift the text so we can decrypt it.
This is a Caesar cypher.
'''
crypticList = []
crypticText = list(cypheredText)
for letter in crypticText:
asciiValue = ord(letter)
# Add some range checking / wrapping here
asciiValue += shiftedCypherNumber
newLetter = chr(asciiValue)
crypticList.append( newLetter )
return ''.join( crypticList )
Creating a list of the string is unnecessary.
You can iterate through the string directly.
for letter in cypheredText:
In order to avoid getting '{', you need to do
some range checking. Since this is based on ASCII
your ranges are:
A-Z = 65-90
a-z = 97-122
When it crosses the end of the range (90 or 122), it
should then come back to the beginning.
That way z wraps to a, and Z to A (for shifting number
of 1). Alternatively, you can just make the entire
string upper/lower case and then not deal with multiple cases.
Ramit
Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list