Skip to content
Advertisement

Best Way to Implement a Custom lower() method in Python

I have an assignment where I’m not allowed to use the .lower() function so I’m creating my own. At the moment I have two ideas on how to do this but would love some input on what the most efficient way would be.

Method 1: Using if elif function

This is the most basic way I could think of, simply passing a character to the method and checking through each letter and returning its lowercase value. I thought this method might be quicker if I put the vowels higher up on the list as they occur the most:

JavaScript

Method 2: Using two Lists:

The second idea I had was to have a list of capital letters and a corresponding list of lowercase letters and would return the index value of the lowecase array at the same position:

JavaScript

I would love to know peoples thoughts on the most efficient way of doing this. Would it be quicker to go with method 2 and implement a quicksort algorithm or what would be the best way?

Thanks!

Advertisement

Answer

Use ord to convert a character into its ASCII value, and chr to convert an ASCII value to its corresponding character. This allows you to translate a character from the uppercase range into the lowercase range just by adding and subtracting:

JavaScript

If you were going to implement it using a lookup table instead of doing ASCII algebra, the more efficient way to build the lookup table would be as a dict, since that gives you constant-time lookups:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement