Question: Python Write a function encipher(s, n) that takes as inputs an arbitrary string s and a non-negative integer n between 0 and 25, and that

Python

Write a function encipher(s, n) that takes as inputs an arbitrary string s and a non-negative integer n between 0 and 25, and that returns a new string in which the letters in s have been rotated by n characters forward in the alphabet, wrapping around as needed. For example:

>>> encipher('hello', 1) result: 'ifmmp' >>> encipher('hello', 2) result: 'jgnnq' >>> encipher('hello', 4) result: 'lipps' 

Upper-case letters should be rotated to upper-case letters, even if you need to wrap around. For example:

>>> encipher('XYZ', 3) result: 'ABC' 

Lower-case letters should be rotated to lower-case letters:

>>> encipher('xyz', 3) result: 'abc' 

Non-alphabetic characters should be left unchanged:

>>> encipher('#caesar!', 2) result: '#ecguct!' 

Hints/reminders:

  • You can use the built-in functions ord and chr convert from single-character strings to integers and back:

    >>> ord('a') result: 97 >>> chr(97) result: 'a' 
  • You can use the following test to determine if a character is between 'a' and 'z' in the alphabet:

    if 'a' <= c <= 'z': 

    A similar test will work for upper-case letters.

  • We recommend writing a helper function rot(c, n) that rotates a single character c forward by n spots in the alphabet. We have given you a template for this helper function in ps3pr3.py that checks to ensure that c is a single-character string. We wrote rot13(c) in lecture; rot(c, n) will be very close to rot13(c)! You can test your rot(c, n) as follows:

    >>> rot('a', 1) result: 'b' >>> rot('y', 2) result: 'a' >>> rot('A', 3) result: 'D' >>> rot('Y', 3) result: 'B' >>> rot('!', 4) result: '!' 
  • Once you have rot(c, n), you can write a recursive encipher function.

Once you think you have everything working, here are three more examples to try:

>>> encipher('xyza', 1) result: 'yzab' >>> encipher('Z A', 2) result: 'B C' >>> encipher('Caesar cipher? I prefer Caesar salad.', 25) result: 'Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc.'

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!