converting letters to numbers

Tim Roberts timr at probo.com
Sun Oct 13 23:13:32 EDT 2013


kjakupak at gmail.com wrote:
>
>Transfer it to an uppercase letter if it's a letter, if it's not then an error.
>This isn't right, I know, just testing around
>
>def add(c1, c2):
>    ans = ''
>    for i in c1 + c2:
>        ans += chr((((ord(i)-65))%26) + 65)
>    return ans

It's close.  I think you're overthinking it.  Take it step by step. Decode,
process, encode.  That means convert the inputs to integers, add the
integers, convert the result back.

def add(c1, c2):
     % Decode
     c1 = ord(c1) - 65
     c2 = ord(c2) - 65
     % Process
     i1 = (c1 + c2) % 26
     % Encode
     return chr(i1+65)

Or, as a one-liner:

A = ord('A')
def add(c1, c2):
     return chr((ord(c1)-A + ord(c2)-A) % 26 + A)
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list