Problem of the Day
A new programming or logic puzzle every Mon-Fri

Text Based Calculator

When trying to use Google's voice search for "7+7" the speech recognition program output "7 plus seven". However, Google's backend was smart enough to realize the answer to the query is 14. Today's goal is to write a program that takes in single digit (zero - nine) numbers in either numeric or alphabetic format and outputs a numeric answer. Some examples:

six plus 4
10

5 + 5
10

0 + eight
8

Permalink: http://problemotd.com/problem/text-based-calculator/

Comments:

  • rizwan - 10 years, 6 months ago

    its enough easy i can do it in just seconds and can write code in minutes

    reply permalink

  • Anonymous - 10 years, 6 months ago

    Simple enum solution I assume?

    reply permalink

  • Max Burstein - 10 years, 6 months ago

    enum would definitely work well here

    reply permalink

  • Ericsson - 10 years, 6 months ago

    Erlang!

    %% Run with escript %% Usage: escript script.erl 1 + one main([First, Operator, Second]) -> FirstNumber = getNumber(First), SecondNumber = getNumber(Second), Function = getFunction(Operator), erlang:display(Function(FirstNumber, SecondNumber)).

    getNumber("zero") -> 0; getNumber("one") -> 1; getNumber("two") -> 2; getNumber("three") -> 3; getNumber("four") -> 4; getNumber("five") -> 5; getNumber("six") -> 6; getNumber("seven") -> 7; getNumber("eight") -> 8; getNumber("nine") -> 9; getNumber(Number) -> N = list_to_integer(Number), case is_integer(N) and ((N >= 0) and (N =< 9)) of true -> N; false -> {error, bad_number} end

    getFunction("+") -> fun(First, Second) -> First + Second end; getFunction("-") -> fun(First, Second) -> First - Second end; getFunction("*") -> fun(First, Second) -> First * Second end.

    reply permalink

  • Anonymous - 10 years, 6 months ago

    texteval = raw_input("Enter something to calculate> ")
    
    textnum = {
        "one" : "1",
        "two" : "2",
        "three" : "3",
        "four" : "4",
        "five" : "5",
        "six" : "6",
        "seven" : "7",
        "eight" : "8",
        "nine" : "9",
        "zero" : "0",
        "plus" : "+",
        "minus" : "-",
        "times" : "*",
        "div" : "/"
    
    }
    
    texteval = texteval.replace("divided by", "div")
    
    texteval = texteval.split(" ")
    
    i = 0
    for item in texteval:
        if item in textnum:
            texteval[i] = textnum[item]
        i = i + 1
    
    print eval(" ".join(texteval))
    

    reply permalink

Content curated by @MaxBurstein