為了不生疏,我想通過解決一些演算法來重繪 我對純 ruby?? 的了解。如果不解決一個較小的演算法,我就無法解決一個較大的演算法,如下例所示。
讓函式 missing_digit(str) 接受str引數,該引數將是一個簡單的數學公式,包含三個數字、一個運算子( , -, *, or /)和一個等號,(=)并回傳完成等式的數字。在等式中的一個數字中,會有一個x字符,您的程式應該確定缺少哪個數字。例如,如果 str 是"3x 12 = 46"那么你的程式應該輸出4.
Examples
Input: "4 - 2 = x"
Output: 2
Input: "1x0 * 12 = 1200"
Output: 0
我想我找到了python的解決方案,但我在任何地方都找不到相應的 Ruby 代碼。
uj5u.com熱心網友回復:
Python 和 Ruby 非常相似,盡管在沒有一些基本 TDD 的情況下嘗試轉換它會很困難。這是從您的 python 示例轉換為 Ruby 檔案。我會重構這段代碼,但這里的簡單測驗通過了,這些測驗在您的鏈接示例中給出。
string_math_x.rb
class StringMathX
def self.calculate(str)
exp = str.split()
first_operand = exp[0]
operator = exp[1]
second_operand = exp[2]
resultant = exp[-1]
# If x is present in resultant
if resultant[/x/]
first_operand = first_operand.to_i
second_operand = second_operand.to_i
if operator == ' '
res = first_operand second_operand
elsif operator == '-'
res = first_operand - second_operand
elsif operator == '*'
res = first_operand * second_operand
else
res = first_operand / second_operand
end
return res
end
# If x in present in operands
# If x in the first operand
if first_operand == 'x'
x = first_operand.to_i
second_operand = second_operand.to_i
if operator == ' '
res = resultant - second_operand
elsif operator == '-'
res = resultant second_operand
elsif operator == '*'
res = resultant / second_operand
else
res = resultant / second_operand
end
# If x is in the second operand
else
x = second_operand.to_i
first_operand = first_operand.to_i
if operator == ' '
res = resultant-first_operand
elsif operator == '-'
res = first_operand - second_operand
elsif operator == '*'
res = resultant.to_i / first_operand.to_i
else
res = first_operand.to_i / resultant.to_i
end
end
res = res.to_s
k = 0
for i in [*0..x]
if i == x
result = res[k]
break
else
k = 1
end
end
result.to_i
end
end
./test/test.rb
require 'minitest/autorun'
require_relative '../lib/string_math_x'
class StringMathXTest < Minitest::Test
def test_basic_subtration
input = '4 - 2 = x'
assert(StringMathX.calculate(input) == 2, 'outputs 2')
end
def test_whats_up_returns_doc
input = '1x0 * 12 = 1200'
assert(StringMathX.calculate(input) == 0, 'outputs 0')
end
end
要運行它,您可能需要 gem install minitest
然后運行 ruby test/test.rb
uj5u.com熱心網友回復:
def findx(str)
s = str.sub('=', '==')
i = s.index('x')
pre = s[0,i]
post = s[i 1..-1]
('0'..'9').find { |d| eval(pre d post) rescue nil }&.to_i
end
findx("4 - 2 = x") #=> 2
findx("1x0 * 12 = 1200") #=> 0
findx("3**x = 81") #=> 4
findx("1/x == 2.0").nil? #=> true
rescue nil在執行除以零的情況下需要。&是安全港運營商。nil如果它之前的部分回傳 ,則它回傳,不考慮后面的所有內容nil。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/338270.html
上一篇:具有has_one關系的模型范圍
