Write another function to convert a value to its word equivalent leveraging the following tuple - o Number = (‘One’, ‘Two’, … ‘Nine’) # Expand this into a tuple o Example: 1234 would be converted to One Two Three Four

Respuesta :

Answer:

  1. def convertStr(num):
  2.    Number = ("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")
  3.    numStr = str(num)
  4.    output = ""
  5.    for x in numStr:
  6.        index = int(x) - 1
  7.        output += Number[index] + " "
  8.    return output
  9. value = 1234
  10. print(convertStr(value))

Explanation:

Firstly, create a function convertStr that take one input number (Line 1).

This function convert the input number to string (Line 3) and then use for-loop to traverse through the individual digit (Line 6). In the loop, get the target index to extract the corresponding digit letter from the Number tuple(Line 7). The target index is always equal to the current digit number - 1. Next, join the extracted digit letter from the tuple to an output string (Line 8) and return it at the end of the function (Line 10).

We test the function using 1234 as argument (Line 12 - 13) and we shall get One Two Three Four

Otras preguntas