M.HBA
M.HBA

Reputation: 71

How to convert string into numbers in python

I see an interesting python exercise in codewars.it is about convert strings to numbers.I want some suggestions or guidance to solve this python exercise.Thank you

this is the exercise:In this kata we want to convert a string into an integer. The strings simply represent the numbers in words. Examples: "one"1

and this is my code:

def parse_int(string):
    dict_of_numbers={ "zero":0, "one":1, "two":2, "three":3, "four":4, "five":5, "six":6, "seven":7, "eight":8, "nine":9,"ten":10, "eleven":11, "twelve":12, "thirteen":13, "fourteen":14, "fifteen":15, "sixteen":16, "seventeen":17, "eighteen":18, "nineteen":19, "twenty":20, "thirty":30, "forty":40, "fifty":50, "sixty":60, "seventy":70, "eighty":80, "ninety":90,"thousand":1000,"hundred":100}

    string=string.replace(' ','-')
    numbers=string.split('-')
    created_number=0
    for number in numbers:
        for key,value in dict_of_numbers.items():
            if number==key:
                created_number+=value
    return created_number

Upvotes: 3

Views: 395

Answers (1)

niaei
niaei

Reputation: 2399

I have a solution and I did not test it for large collection of numbers but it may give you some ideas:

  1. Spoken numbers sometimes are summed sometimes are multiplied.
  2. Some times people put an and between numbers. Like: thirty seven thousand and twenty one
  3. Don't use [] to get value from your dictionary. Use get method. So if there is not data corresponding to the number you have control over the return.
  4. use str's .lower() to lower the letters in the string to avoid upper case, lower case problem

The code I wrote would look like:

def parse_int(string):
    dict_of_numbers = {"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7,
                       "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14,
                       "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18, "nineteen": 19, "twenty": 20,
                       "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90,
                       "thousand": 1000, "hundred": 100}

    string = string.replace(" and ", " ")
    the_number = 0
    for each in string.lower().split():
        if each in ["hundred", "thousand"]:
            the_number *= dict_of_numbers.get(each, 1)
        else:
            the_number += dict_of_numbers.get(each, 0)


    return the_number


print(parse_int("thirty seven thousand and twenty two")) # 37022

Upvotes: 1

Related Questions