# [Tutor] a function I fail to understand

Dave Angel davea at ieee.org
Tue Mar 22 06:45:07 CET 2011

```On 01/-10/-28163 02:59 PM, Alex Hall wrote:
> On 3/21/11, David<ldl08 at gmx.net>  wrote:
>> Hello list,
>>
>> I am having trouble understanding the following function. What trips me
>> up is the "letter = letter.lower()" line.
>>
>> As I understand, the function takes a letter and assigns True to a
>> letter if it is upper case.
> No, the function takes a letter and returns that letter in its uppercase form.
> lr="a"
> lr.upper() #lr now = A
> lr.lower() #lr now equals a
> I should actually say that it takes a string and uppercases any
> letters in it. It just happens that you are dealing with one letter
> here.

Not even close.  The CHAR_MAP is apparently a map from char to char,
where both are presumably lower-case ones.  My suspicion is the map
looks like:

CHAR_MAP = { "a":"n", "b", "o", ...   "z":"m"}

The code simply returns its input if it's not represented in the map.
But if the letter is lowercase, it's just looked up in the map, and the
result is returned.  if the letter is uppercase, it's changed to
lowercase, looked up, then changed back to uppercase.

The code could have been trivial if the map had simply had both lower
and uppercase entries in it to begin with.  The table would be twice the
size, but the code would then have been trivial.

Of course, the maketrans function could have simplified it even more.
Or you could just use the rot_13 encoder:

>>> import codecs
>>> f = codecs.getencoder("rot_13")
>>> f("Abcde")
('Nopqr', 5)

DaveA

>>
>> But then he goes to
>>
>> letter = letter.lower()
>>
>> and all letters are converted back to lower again!?? The point is that,
>> to my understanding, the logic follows from the first block to
>> letter = letter.lower(). Isn't that true?
>>
>> Thanks for helping me out,
>>
>> David
>>
>>
>> def rotate13_letter(letter):
>>      """
>>      Return the 13-char rotation of a letter.
>>      """
>>      do_upper = False
>>      if letter.isupper():
>>          do_upper = True
>>
>>      letter = letter.lower()
>>      if letter not in CHAR_MAP:
>>          return letter
>>
>>      else:
>>          letter = CHAR_MAP[letter]
>>          if do_upper:
>>              letter = letter.upper()
>>
>>      return letter
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>

```