0

I want to be able to add two numbers that are inputted by the user (as strings), and then output the result still as a string. For example:

Input 1 - 'three' Input 2 - 'seven'

Output - 'ten'

I am trying to do this without using any external libraries.

I first tried creating a list and matching each entry up with its index number, but this proved to be highly inefficient.

numbers = ['zero','one','two','three','four'... number = numbers[index]

1 Answers1

1

You could use a dictionary to convert numbers like 'one' to digits as in this simplified example:

conv = {
    'one': 1,
    'two': 2,
    'three': 3,
    }

num1s = 'one'
num2s = 'two'

result = conv[num1s] + conv[num2s]

for key, val in conv.items():
    if val == result:
        print(key)
        break

which prints three

user19077881
  • 3,643
  • 2
  • 3
  • 14
  • Wow. Thanks for finding the most inefficient solution to my problem! Really smart. Lets make a dictionary where we need to add two pieces of data for each number rather than a list where we could just use one (index+1). Also, nice break – sneedham16 Feb 02 '23 at 13:34
  • The Dictionary look-up using its hash table takes around 0.05 micro-seconds. How do you define inefficient? – user19077881 Feb 02 '23 at 14:48
  • Wow, I didn't think of it like that. JK! How about inefficient in terms of how much code you are having to write? Why on earth would you do twice as much writing for something you can do with a list of strings and just taking there index. Also, nice break – sneedham16 Feb 03 '23 at 15:03
  • With a small example like yours you can do it anyway that works. But try: three thousand and forty three plus seven hundred and two. Its easy to psrse and use a Dictionary with just a few entries : one to nineteen, twenty to ninety. hundred, thousand etc. The break expression is fine. I think its better to offer general solutions here. – user19077881 Feb 03 '23 at 16:59