exercism / julia

Exercism exercises in Julia.
https://exercism.org/tracks/julia
MIT License
66 stars 69 forks source link

add practice exercise wordy #756

Closed depial closed 1 month ago

depial commented 1 month ago

Adding practice exercise wordy according to problem-specifications. A couple things to note:

That is all for the note for the implementation, but there is something I've found about being able to "hack" the error handling questions.

Below is an algorithm which doesn't use regex. Please note the line which is commented out:


ENG2MATH = zip(("plus","minus","divided by","multiplied by","What is ","?"), ("+","-","/","*","",""))
ops = Dict(zip(("+","-","/","*"), (+,-,/,*)))

function wordy(problem)
    foreach(op -> problem = replace(problem, first(op) => last(op)), ENG2MATH)
    terms = split(problem)
    #iseven(length(terms)) && throw(ArgumentError(problem)) 
    total, operands = parse(Int, first(terms)), [+, 0]
    for (i, term) in enumerate(terms[2:end])
        try 
            operands[mod1(i, 2)] = isodd(i) ? ops[term] : parse(Int, term)
        catch error
            throw(ArgumentError(problem)) 
        end 
        iseven(i) && (total = first(operands)(total, last(operands)))
    end
    iseven(length(terms)) ? throw(ArgumentError(problem)) : total
end

When that line is commented in, and other error handling isn't implemented (i.e. try/catch block and final trinary), this will pass 7 out of 8 of the error handling tests, while it is only valid for two of them. The others that pass are "happy coincidences". For example, it passes with input "Who is the President of the United States?" but wouldn't pass "Who is the Prime Minister of India", simply because of word count (since a valid math expression has to have an odd number of operands). I'm not sure if this loophole should be changed or not

depial commented 1 month ago

Some potential added tests to address the loophole mentioned above:

    @testset "unknown operation" begin
        @test_throws ArgumentError wordy("What is 52 squared plus square root of 5?")
    end

    @testset "Non math question" begin
        @test_throws ArgumentError wordy("Who is the Prime Minister of India?")
    end

    @testset "reject two operations in a row" begin
        @test_throws ArgumentError wordy("What is 1 plus plus 2 minus minus 3?")
    end

    @testset "reject two numbers in a row" begin
        @test_throws ArgumentError wordy("What is 1 plus 2 1 plus 3 4?")
    end