Connecting Tech Pros Worldwide Help | Site Map

have to wrte a code for the below program

Newbie
 
Join Date: Aug 2009
Posts: 2
#1: Aug 19 '09
hi i have to write pyhton code for the program below..i have tried doin it but could not get the desired result so if anyone can help me out i would be very thankful.the question is as below..

A Caesar cipher is a simple substitution cipher based on the idea of shifting
each character in a message a fixed number of positions in the alphabet (the
fixed number is called the key). For example “apple” would become “bqqmf”
with a key of 1, and the initial message could be recovered using a key of -1.

Write a program program which encodes a text file using the Caesar cipher
and output the result to a file of the same name with a “.xxx” appended to it.
Your program will need to prompt the user for the name of the text file
containing the initial message and the key to be used.

You will need to use the chr() function to solve this problem. For example if
you wanted to shift a character (lets call it ch) 2 places you could do so in
Python with chr(ord(ch)+2).

Finally modify your Caesar cipher to use two separate keys. The first key
would shift every odd numbered character and the second key every even numbered character.

Above is the question what i have to do it is only a single question
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#2: Aug 19 '09

re: have to wrte a code for the below program


fury30,

We are not here to do your homework for you. I can give you some examples that should get you started.

Expand|Select|Wrap|Line Numbers
  1. >>> s = "This sentence will be scrambled"
  2. >>> key = 3
  3. >>> cipher = [ord(c)+key for c in s]
  4. >>> print ''.join([chr(i) for i in cipher])
  5. Wklv#vhqwhqfh#zloo#eh#vfudpeohg
  6. >>> cipher = [ord(c)-key for c in 'Wklv#vhqwhqfh#zloo#eh#vfudpeohg']
  7. >>> print ''.join([chr(i) for i in cipher])
  8. This sentence will be scrambled
  9. >>> 
Example using string.maketrans:
Expand|Select|Wrap|Line Numbers
  1. s = "This sentence will be scrambled"
  2. >>> import string
  3. >>> m = string.maketrans('abcdefghijklmnopqrstuvwxyz', 'cdefghijklmnopqrstuvwxyzab')
  4. >>> s1 = string.translate(s, m)
  5. >>> s1
  6. 'Tjku ugpvgpeg yknn dg uetcodngf'
  7. >>> 
Example using a dictionary:
Expand|Select|Wrap|Line Numbers
  1. >>> cipher = {"a":"g", "b":"h", "c":"i", "d":"j", "e":"k", "f":"l", "g":"m", "h":"n", \
  2.           "i":"o", "j":"p", "k":"q", "l":"r", "m":"s", "n":"t", "o":"u", "p":"v", \
  3.           "q":"w", "r":"x", "s":"y", "t":"z", "u":"a", "v":"b", "w":"c", "x":"d", \
  4.           "y":"e", "z":"f"}
  5.  
  6. >>> s = "This sentence will be scrambled"
  7. >>> print ''.join([cipher.get(c, c) for c in s])
  8. >>> Tnoy yktzktik corr hk yixgshrkj
Reply