Last active
January 10, 2021 01:29
-
-
Save AdityaBhutani/7577c6e62bab8c32902868c42f9419d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# str = "3x + 2 + x/6 = 5", expected: 0.94736 | |
# str = "3x = 9", expected: 3.0 | |
# str = '3x - 2 + x/6 = 5', expected: 2.21 | |
# program to solve linear equation with arg as str format of linear eqn. | |
def linear_equation(str) | |
elements = str.split(' ') | |
nums = [] | |
xs = [] | |
signs = ['+', "-"] | |
next_sign = 1 | |
n = elements.size | |
elements[0..(n-3)].each do |ele| | |
if ele.include?('x') | |
out = ele[/\d+/].to_f | |
out = 1.0/out if ele.include?('/') | |
xs << out*next_sign | |
next | |
end | |
if ele.exclude?('+') && ele.exclude?('-') | |
nums << ele[/\d+/].to_f*next_sign | |
next | |
end | |
next_sign = case ele | |
when "+" | |
1 | |
when "-" | |
-1 | |
end | |
end | |
a = xs.sum | |
b = nums.compact.sum | |
c = elements.last.to_i | |
return (c-b)/a | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment