你必須很努力

Day29 - Codewars 刷題

2019/10/08
字數統計: 169閱讀時間: 1 min

挑戰 Codewars LV3 題目


題目(Calculator)

1
2
3
4
5
6
Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression

Example:

Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.

1
2
3
4
5
6
7
8
9
10
11
12
class Calculator
def evaluate(string)
end
end

calc = Calculator.new

Test.assert_equals(calc.evaluate("4 + 5"), 9)
Test.assert_equals(calc.evaluate("4 * 5"), 20)
Test.assert_equals(calc.evaluate("4 / 5"), 0.8)
Test.assert_equals(calc.evaluate("4 - 5"), -1)
Test.assert_equals(calc.evaluate("4 + 5 * 6"), 34)


影片解題:


答案:

1
2
3
4
5
6
7
8
9
10
11
# Calculator
class Calculator
def evaluate(string)
['+', '-', '*', '/'].each do |cal|
if string.include?(cal)
return string.split(cal).map{ |x| evaluate(x) }.inject(cal.strip)
end
end
string.to_f
end
end

本文同步發布於 小菜的 Blog https://riverye.com/

原文連結:https://riverye.com/2019/10/08/Day29-Codewars-刷題/

發表日期:2019-10-08

更新日期:2022-12-21

CATALOG