简体   繁体   中英

Recursive function that prints digits of a number in english

I am working on a program that uses a recursive function to print the digits of a number in English (ie 456 would display "Four Five Six".) I noticed someone else recently asked this question but I was unable to get any help from it. The program also requires that multiple numbers be entered from a user and each one should have the corresponding English digits displayed. I tried doing this in a list but am unsure if that is correct.

Right now I am beyond confused. I have been working on this for hours now and do not have much to show for it. I'm not looking for anyone to write this program for me, just offer some assistance. In theory I know what needs to be done but I'm having a very difficult time translating that into code.

def main():
    List = createList()
    print(createList())

def listValue(prompt):
    try:
        number = eval(input(prompt))
        if type(number) == type(0) or type(number) == type(0.0):
            return number
        else:
            print("\nYou did not enter a number. Try again.")
    except NameError:
        print("\nYou did not enter a number. Try again.")
    except SyntaxError:
        print("\nYou did not enter a number. Try again.")
    except:
        print("\nAn exception occured. Try again.")
    if number != "":
        return number
   else:
        return None

def createList():
    #Create a blank list
    newList = []
    item = listValue("Enter a list of numbers (<Enter> to quit): ")
    while item != None:
        #Add user input to the end of the created list
        newList.append(item)
        item = listValue("Enter a list of numbers (<Enter> to quit): ")
    return newList


def displayEnglishDigits(number): 
    numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
    digit = Number % 10


main()

here is the updated version of my code... any thoughts?

    def getNumbers():
        n = []
        xStr = input("Enter first digit of number (negative to quit) >> ")
        integer = int(xStr)
        while  integer >= 0:
            while xStr != "":
                x = eval(xStr)
                n.append(x)
                xStr = input("Enter next digit of number (negative to quit) >> ")
        return n

    def displayEnglishDigits(number):
        numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                      5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
        number = getNumbers()
        if len(number) == 0:
             return None
        if len(number) == 1:
            return number[0]
       else:
            value = displayEnglishDigits(number[1:])
       return value

    def display(values):
        print(displayEnglishDigits(number))

    def main():
        numb = getNumbers()
        nums = displayEnglishDigits(numb)
        display(nums)

    main()

Let's focus on the recursive function, since that's the title.

You've got a good start with the numEnglish dictionary.

To finish it off, why not try: turn the number into a string (a list of characters), and write a recursive function that processes the list.

numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
              5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}

def recursiveDisplay(stringOfNumber):
    if len(stringOfNumber) == 0:            # base case: empty string
      return
    first = int(stringOfNumber[0])          # otherwise, grab the first element
    english = numEnglish[first]             # look it up in the dictionary
    print english                           # print it
    recursiveDisplay(stringOfNumber[1:])    # and recurse on the rest of the list

The recursive function has two cases:

  • 1) the string is empty: done processing. This is the base case .
  • 2) the string is not empty: process the first element, and issue a recursive call with everything but the first element. This is the inductive/recursive case.

Note that the dictionary numEnglish is now defined outside of the recursive function.


When you call recursiveDisplay , make sure to pass it a string!

recursiveDisplay(str(myNumber))

Disclaimer: using recursion for list processing is not standard python!

I know it is possible you need this for the learning purposes, but anyways:

Do not do it recursively.

There are simpler ways to do it and you will not be limited by the max recursion limit set for Python. Just use the following solution:

>>> def print_number(some_number):
    for cipher in str(some_number):
        print ['Zero', 'One', 'Two', 'Three', 'Four',
               'Five', 'Six', 'Seven', 'Eight', 'Nine'][int(cipher)],
    print


>>> print_number(126321)
One Two Six Three Two One

It works like a charm :)

Please find my piece of code for the same, please lemme if its possible reduce further.

from __future__ import print_function

helper={}
helper = {1:"one",
        2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine",
0:""}

face = {}
face = { 0:"zero",
1:
        {0:"",
        1:
                {0:"ten",
                1:"eleven",
                2:"twelve",
                3:"thirteen",
                4:"fourteen",
                5:"fifteen",
                6:"sixteen",
                7:"seventeen",
                8:"eighteen",
                9:"ninteen"
        },
        2:"twenty",
        3:"thirty",
        4:"fourty",
        5:"fifty",
        6:"sixty",
        7:"seventy",
        8:"eighty",
        9:"ninety"},
2:"hundred",
3:"thousand"}

result = ""
teen = ""

def rec_ntw(number, face_value=0):
        global result
        global teen
        if number <= 0:
                if face_value == 0:
                        result = "Zero"
                print (result)
                #return result
        else:
                if face_value == 0:
                        result = (helper[int(number % 10)])
                        teen = number % 10
                elif face_value == 1:
                        if number % 10 == 1:
                                result = (face[1][1][int(teen)]) + " "
                        else:
                                result = (face[int(face_value)][int(number % 10)]) + " " + result
                                teen = 0
                elif face_value == 2:
                        if number % 10 != 0:
                                result = (helper[int(number % 10)] + " " + str(face[int(face_value)]) + " ") + result
                else:
                        result = (helper[int(number % 10)] + " " + str(face[int(face_value)]) + " ") + result
                face_value += 1
                rec_ntw(number // 10, face_value)



while True:
        try:
                user_input = input("Please enter the number: ")
                rec_ntw(user_input)
        except KeyboardInterrupt:
                break

Try this:

numEnglish  = { 0:'zero ', 1:'one ', 2:'two ', 3:'three ', 4:'four ',
                5:'five ', 6:'six', 7:'seven ', 8:'eight ', 9:'nine ' }

def displayEnglishDigits(number):
    if number == 0:
        return ""
    digit = numEnglish[number % 10]
    return displayEnglishDigits(number / 10) + digit

Two things to take into account: first, you have to define the num_names dictionary as shown above. Second, there's one special case to be aware of - if the number is just 0, print "zero". Otherwise, call displayEnglishDigits . Also notice that de procedure returns a string with the digits, you can print it afterwardws.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM