1
\$\begingroup\$

I made this simple program that can solve every set of linear equations in two variables.

You just need to enter two linear equations of the form ax+by=c (without any unnecessary spaces) where 'a' is a positive integer (i.e. x should not have a negative coefficient) and b and c are just integers.

The program can also show outputs like "The two equations have no solution" or "the two equations have infinite solutions" if it is so...

I only used the knowledge of 9th and 10th grade Python along with the concept of functions to make this program and I will update it on the basis of the suggestions that I got from some great people in my last question. I will try to make it shorter, more readable and definitely more efficient soon, will post that too when done.

Here's the Python code :

def getindex(a,b):
 size = len(b)
 status = 0
 for i in range(0,size,1):
 element = b[i]
 if (element == a):
 index = i
 status = 1
 break
 if (status == 1):
 return index
 else:
 return "not found"
def getstring(a,b,c):
 string = c[a]
 for i in range(a+1,b,1):
 element = c[i]
 string = string + element
 return string
def lcm(a,b):
 found = False
 if (a>b):
 larger = a
 else:
 larger = b
 i = larger
 while found == False:
 if (i%a == 0) and (i%b == 0):
 found = True
 break
 else:
 i += larger
 return i
print ()
print ("Please enter two equations of the form ax+by=c where a is a positive integer and b and c are integers...")
print ()
a = str(input("Please enter the first equation : "))
b = str(input("Please enter the second equation : "))
a = list(a)
b = list(b)
sizea = len(a)
sizeb = len(b)
# Getting a, b and c of equation one
symbolindexone = getindex('+',a)
equalindexone = getindex('=',a)
symbolstatusone = "positive"
if (symbolindexone == "not found"):
 symbolindexone = getindex('-',a)
 symbolstatusone = "negative"
xindexone = getindex('x',a)
yindexone = getindex('y',a)
a1 = getstring(0,xindexone,a)
if (a1 == 'x'):
 a1 = 1
else:
 a1 = int(a1)
b1 = getstring(symbolindexone+1,yindexone,a)
if (b1 == 'y'):
 if (symbolstatusone == 'positive'):
 b1 = 1
 else:
 b1 = -1
else:
 b1 = int(b1)
 if (symbolstatusone == "negative"):
 b1 = -b1
c1 = getstring(equalindexone+1,sizea,a)
c1 = int(c1)
# getting a, b and c of equation two
symbolindextwo = getindex('+',b)
equalindextwo = getindex('=',b)
symbolstatustwo = 'positive'
if (symbolindextwo == 'not found'):
 symbolindextwo = getindex('-',b)
 symbolstatustwo = 'negative'
xindextwo = getindex('x',b)
yindextwo = getindex('y',b)
a2 = getstring(0,xindextwo,b)
if (a2 == 'x'):
 a2 = 1
else:
 a2 = int(a2)
b2 = getstring(symbolindextwo+1,yindextwo,b)
if (b2 == 'y'):
 if (symbolstatustwo == 'positive'):
 b2 = 1
 else:
 b2 = -1
else:
 b2 = int(b2)
 if (symbolstatustwo == 'negative'):
 b2 = -b2
c2 = getstring(equalindextwo+1,sizeb,b)
c2 = int(c2)
# LCM and the final phase
lcma = lcm(a1,a2)
tmbone = lcma/a1
tmbtwo = lcma/a2
a1 *= tmbone
b1 *= tmbone
c1 *= tmbone
a2 *= tmbtwo
b2 *= tmbtwo
c2 *= tmbtwo
ratioa = a1/a2
ratiob = b1/b2
ratioc = c1/c2
print ()
if (ratioa == ratiob == ratioc):
 print ("The equations that you entered have infinite solutions...")
elif ((ratioa == ratiob) and (ratioa != ratioc)):
 print ("The equations that you entered have no solution...")
else:
 ysolution = (c1-c2)/(b1-b2)
 xsolution = ((c1)-(b1*ysolution))/(a1)
 print ("The value of x is : ",xsolution)
 print ("The value of y is : ",ysolution)

Let me know what you think

Thanks :)

asked Mar 27, 2020 at 7:10
\$\endgroup\$
7
  • \$\begingroup\$ Do you want to use built-in functions or not? There are functions in the Python library for get_index and getstring \$\endgroup\$ Commented Mar 27, 2020 at 11:10
  • \$\begingroup\$ @DaniMesejo Of course I do but I don't have much knowledge about Python (yet), it hasn't even been one year since I began Python. The reason I began posting programs here is because I want to learn how I can make the program more efficient and I just found out yesterday about the built-in functions, I'm gonna use them in the other programs as soon as I learn more about them. \$\endgroup\$ Commented Mar 27, 2020 at 11:17
  • \$\begingroup\$ What is the function lcm suppose to do? Least Common Multiple? \$\endgroup\$ Commented Mar 27, 2020 at 11:27
  • \$\begingroup\$ Yes, the program finds the coefficients of x in both the equations, finds the LCM, and then calculates how much to multiply both the equations by in order to equalize the coefficients of x so that it can eliminate x by subtracting the new equations and find the value of y. It then substitutes the value of y in one of the equations to find the value of x. \$\endgroup\$ Commented Mar 27, 2020 at 11:55
  • \$\begingroup\$ Shouldn't the LCM greater that both numbers? \$\endgroup\$ Commented Mar 27, 2020 at 12:09

1 Answer 1

2
\$\begingroup\$

Some comments:

  1. Rename functions to follow the PEP8 naming convention, here.
  2. Do not use range to iterate over the a list of elements, iterate directly over it. If you need the index, as in your case, use enumerate.
  3. No need to wrap the boolean clauses in parenthesis, moreover you can use the truth(y) values directly, see truth value testing.
  4. Is possible add comments on what does the function does.

After a first rewrite the code of your function should look something like this:

def get_index(a, b):
 """Get the index of and element or else return 'not found' """
 status = 0
 index = 0
 for i, element in enumerate(b):
 if element == a:
 index = i
 status = 1
 break
 if status:
 return index
 else:
 return "not found"
def get_string(a, b, c):
 """Build a sub-string from c starting on a"""
 string = c[a]
 for i in range(a + 1, b, 1):
 element = c[i]
 string = string + element
 return string
def lcm(a, b):
 """Find the least common multiple"""
 if a > b:
 larger = a
 else:
 larger = b
 i = larger
 while True:
 if (i % a == 0) and (i % b == 0):
 break
 else:
 i += larger
 return i
if __name__ == "__main__":
 assert get_index(1, [1, 2, 3]) == 0
 assert get_index(1, [2, 3]) == "not found"
 assert get_string(0, 3, "hello world") == "hel"
 assert lcm(2, 5) == 10

I added some (basic) test, to validate any further change you could make in the future to this functions.

The above comments are superficial, if you want speed and reliability use the functions provided by the standard library, in the end your functions should look like something like this:

from math import gcd
def get_index(a, b):
 """Get the index of and element or else return 'not found' """
 try:
 return b.index(a)
 except ValueError:
 return "not found"
def get_string(a, b, c):
 """Build a sub-string from c starting on a"""
 return c[a:b]
def lcm(a, b):
 """Find the least common multiple"""
 return abs(a * b) // gcd(a, b)

The lcm implementation uses the gcd, see more in the wikipedia page.

answered Mar 27, 2020 at 13:06
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thanks, awesome suggestions, I actually thought about the gcd method, because product of numbers = lcm*hcf but when I wrote the code, I found it to be even longer. Didn't know gcd was an in-built function, thanks for letting me know... \$\endgroup\$ Commented Mar 27, 2020 at 16:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.