No Numerals
Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.
Contents
Problem ¶
You write a phrase and include a lot of number characters (0-9), but you decide that for numbers 10 and under you would rather write the word out instead. Can you go in and edit your phrase to write out the name of each number instead of using the numeral?
Task:
Take a phrase and replace any instances of an integer from 0-10 and replace it with the English word that corresponds to that integer.
Input Format:
A string of the phrase in its original form (lowercase).
Output Format:
A string of the updated phrase that has changed the numerals to words.
Sample Input:
i need 2 pumpkins and 3 apples
Sample Output:
i need two pumpkins and three apples
Solution ¶
Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.
import re
num2txt={'0':'zero','1':'one','2':'two','3':'three','4':'four','5':'five',
'6':'six','7':'seven','8':'eight','9':'nine','10':'ten'}
print(re.sub('\d{1,2}',lambda num:num2txt[num[0]],input()))
Explanation ¶
My approach (or the algorithm)¶
- Create a dictionary with numbers and them in words as key-value pairs upto 10.
- Find numbers from 0 to 10 in the input and replace them with words.
The code¶
- This is the dictionary we talked about
num2txt={'0':'zero','1':'one',...}
-
re.sub()
substitutes a match with another string. -
'\d{1,2}'
is a RegEx pattern to find any one or 2 digit numbers in the input. -
lambda num:num2txt[num[0]]
is a lambda function that takes the RegEx match (i.e, the number) and returns the corresponding word from the dictionary. The first element of the match object contains the match or the number, so we need to usenum[0]
instead ofnum
.
The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.
Last updated 2021-01-09 15:19:26.054280 IST
Comments