converting letters to numbers

Dave Angel davea at davea.name
Tue Oct 8 17:24:03 EDT 2013


On 8/10/2013 10:28, kjakupak at gmail.com wrote:

> I have to define a function add(c1, c2), where c1 and c2 are capital letters; the return value should be the sum (obtained by converting the letters to numbers, adding mod 26, then converting back to a capital letter). 
>
> All I have so far is:
>
> def add(c1, c2):
>     ord(c1) - ord('a') + 1
>     ord(c2) - ord('a') + 1
>
> I know I need to use ord and chr, just not sure how.


Factor the problem into three functions.  one function converts a
one-character string into an int, or gives an exception if the
character. isn't uppercase ASCII.

Second function converts a small int into a string containing one
uppercase ASCII letter, throwing an exception if negative or above 25.

Third function takes two string arguents, throws an exception if either
of them is not exactly one character in length.  Then it calls the first
function twice, adds the results, modulos it, and calls the second
function, returning its return value.

Which of these is giving you trouble?  Notice you can use the first two
functions to test each other.

-- 
DaveA





More information about the Python-list mailing list