Python program to convert a given number into wordsIn this article, you will learn how to convert a given number into words. There are various approaches that help to convert a given number into words. Approach 1:An approach can be as follows: Output: Enter a number: 8955 eight thousand nine hundred fifty-five The step-by-step implementation can be described as follows:
Time Complexity The time complexity of the convert_to_words function is O(log n), where n is the input number. It is because the function performs a constant number of operations for each digit of the input number, and the number of digits in the input is proportional to the logarithm of the input value. Specifically, the function checks for the presence of each magnitude (thousands, hundreds, etc.) in turn, and then extracts the appropriate digit(s) and looks up the corresponding word(s) from pre-defined lists. Therefore, the time taken by the function will grow slowly as the input number increases, making it an efficient algorithm for converting numbers to words. Approach 2There are other approaches to converting a number to words in Python. One such approach is to use a recursive function to handle the different magnitudes of the number. Here is an example of how you could implement this approach: Output: One thousand two hundred thirty-four
Approach 3Another approach to convert a number to words in Python is to use a dictionary to map the digits to their corresponding words. Here is an example of how you could implement this approach: Explanation: We define a dictionary digits_to_words that maps each digit from 0 to 9 to its corresponding word. We define a list of magnitudes and their corresponding names (magnitudes). The first magnitude is 1 (for the units digit), and each subsequent magnitude is a power of 10 (3, 6, 9, etc.), along with its corresponding name ("thousand", "million", "billion", etc.).
Time Complexity The time complexity of this algorithm is O(log(n)), where n is the input number. It is because we loop through the magnitudes in reverse order, which takes O(log(n)) iterations in the worst case (for very large numbers). Within each iteration, the operations we perform (extracting the current group of digits, converting them to words, etc.) take constant time. Space Complexity The space complexity of the algorithm is also O(log(n)), because we store the words for each group of digits in a list (words). The length of this list is proportional to the number of magnitudes (which is O(log(n))), and each word takes constant space. The other data structures we use (the digits_to_words dictionary and the magnitudes list) also take constant space. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India