Equation Solver

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.

Equation Solver

Postby luis.simao.af98 » Sun Jun 16, 2013 5:44 pm

Hi all! I'm here to show you my first project on Python - a simple equation solver. For now, it only solves 1st and 2nd degree equations with 1 variable, however it has worked fine for me until now. I intend to add more features, such as solving equation systems. Anyway, I hope you enjoy it and please let me know about any bugs or suggestions!

Code: Select all
print('''Welcome to:

+--------------------+
|EQUATION SOLVER V0.2|
+--------------------+

by: Luís Ferreira
''')

#module imports
import time
import math

#defining functions
def continue1choice():
    continue1 = input('Do you want to solve more equations? (y/n) ')
    if continue1 == 'y':
        EquationSolver()
    elif continue1 == 'n':
        print('Thank you for checking my app!')
        time.sleep(3)
    elif continue1 != 'y' and continue1 != 'n':
        print('You must chose "y" (yes) or "n" (no)!')
        continue1choice()

def EquationSolver():
    EquationType = input('Equations degree (1st or 2nd): ')
    if EquationType == '1st':
        def solve1(eq,var='x'):
            eq1 = eq.replace("=","-(")+")"
            c = eval(eq1,{var:1j})
            print(-c.real/c.imag)
        eq = input('Type your equation here (use "x" as variable): ')
        solve1(eq,var='x')
        time.sleep(2)
        continue1choice()
    elif EquationType == '2nd':
        def solve2():
            print('Your equation is, in the canonical form: a*x^2 + b*x + c = 0')
            a = int(input('Assign a value to "a": '))
            b = int(input('Assign a value to "b": '))
            c = int(input('Assign a value to "c": '))
            delta = b**2 - 4*a*c
            if delta < 0:
                print('The equation is impossible - it has 0 solutions.')
                continue1choice()
            elif delta == 0:
                x = -b
                print('Your equation has 1 solution, which is %r.' % r)
                continue1choice()
            elif delta > 0:
                pass
            sqrtDelta = math.sqrt(delta)
            x1 = (-b + sqrtDelta)/2*a
            x2 = (-b - sqrtDelta)/2*a
            print('Your equation has 2 solutions, which are %r and %r.' %(x1, x2))
        solve2()
        continue1choice()
def MainMenu():
    print('- MAIN MENU -')
    print('What do you want to do?')
    print('''[1] Start solving equations
[2] More info
[3] Quit''')
    option1 = input(':: ')
    if option1 == '1':
        EquationSolver()
    elif option1 == '2':
        print('''- More info -
This small app, Equation Solver, was totally made by me,
Luís Ferreira, in order to use it for educational purpo-
ses for me (to start working better with Python) and for
others too, as a suplement to their education in Math. I
hope that you comprehend that there maybe many mistakes
with the code, since I'm relativly new to Python and sin-
ce this project is still in a very fresh fase. However,
I don't want to make this like Sympy or other equation
solvers - although I used some useful tips and code avai-
lable on the internet. I hope you enjoy it and let me know
about any mistakes or sugestions.
Thank you for trying it!''')
        input('Press [enter] to continue')
        print('')
        MainMenu()
    elif option1 == '3':
        print('Thank you for checking my app!')
        time.sleep(3)
    elif option1 != '1' and option1 != '2' and option1 != '3':
        print('You must chose an available option!')
        MainMenu()

#proper execution
MainMenu()


Best regards,
Luis Ferreira.
Last edited by luis.simao.af98 on Mon Jun 17, 2013 3:18 pm, edited 1 time in total.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby luis.simao.af98 » Sun Jun 16, 2013 8:10 pm

FIX 1.1:
- While solving 2nd degree equations, if all values were 0, the app would crash.
- Minor math error corrected.

Code: Select all
print('''Welcome to:

+----------------------+
|EQUATION SOLVER V0.2.1|
+----------------------+

by: Luís Ferreira
''')

#module imports
import time
import math

#defining functions
def continue1choice():
    continue1 = input('Do you want to solve more equations? (y/n) ')
    if continue1 == 'y':
        EquationSolver()
    elif continue1 == 'n':
        print('Thank you for checking my app!')
        time.sleep(3)
    elif continue1 != 'y' and continue1 != 'n':
        print('You must chose "y" (yes) or "n" (no)!')
        continue1choice()

def EquationSolver():
    EquationType = input('Equations degree (1st or 2nd): ')
    if EquationType == '1st':
        def solve1(eq,var='x'):
            eq1 = eq.replace("=","-(")+")"
            c = eval(eq1,{var:1j})
            print(-c.real/c.imag)
        eq = input('Type your equation here (use "x" as variable): ')
        solve1(eq,var='x')
        time.sleep(2)
        continue1choice()
    elif EquationType == '2nd':
        def solve2():
            print('Your equation is, in the canonical form: a*x^2 + b*x + c = 0')
            a = int(input('Assign a value to "a": '))
            b = int(input('Assign a value to "b": '))
            c = int(input('Assign a value to "c": '))
            delta = b**2 - 4*a*c
            if delta < 0:
                print('The equation is impossible - it has 0 solutions.')
                continue1choice()
            elif a == 0 and b == 0:
                print('The equation is impossible - it has 0 solutions.')
                continue1choice()
            elif delta == 0:
                x = -b
                print('Your equation has 1 solution, which is %r.' % r)
                continue1choice()
            elif delta > 0:
                pass
            sqrtDelta = math.sqrt(delta)
            x1 = (-b + sqrtDelta)/2*a
            x2 = (-b - sqrtDelta)/2*a
            print('Your equation has 2 solutions, which are %r and %r.' %(x1, x2))
        solve2()
        continue1choice()
def MainMenu():
    print('- MAIN MENU -')
    print('What do you want to do?')
    print('''[1] Start solving equations
[2] More info
[3] Quit''')
    option1 = input(':: ')
    if option1 == '1':
        EquationSolver()
    elif option1 == '2':
        print('''- More info -
This small app, Equation Solver, was totally made by me,
Luís Ferreira, in order to use it for educational purpo-
ses for me (to start working better with Python) and for
others too, as a suplement to their education in Math. I
hope that you comprehend that there maybe many mistakes
with the code, since I'm relativly new to Python and sin-
ce this project is still in a very fresh fase. However,
I don't want to make this like Sympy or other equation
solvers - although I used some useful tips and code avai-
lable on the internet. I hope you enjoy it and let me know
about any mistakes or sugestions.
Thank you for trying it!''')
        input('Press [enter] to continue')
        print('')
        MainMenu()
    elif option1 == '3':
        print('Thank you for checking my app!')
        time.sleep(3)
    elif option1 != '1' and option1 != '2' and option1 != '3':
        print('You must chose an available option!')
        MainMenu()

#proper execution
MainMenu()
Last edited by luis.simao.af98 on Mon Jun 17, 2013 3:18 pm, edited 1 time in total.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby micseydel » Mon Jun 17, 2013 12:36 am

I recommend:
Pep 8.
A repository, like Github or Bitbucket.
No comments like "imports" when the comment contents are clear from the code.
Not using nested functions. They're a great language feature, but they're not a good idea here.
Separation of interface from implementation. I'm not a fan of the sleep()s either.

And more advice once the code is cleaned up from what it is.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1354
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 10:24 am

Sorry, but I'm still really new to Python, so could you please explain yourself better? Why pep8? Why using a repository? What do you mean with "nested functions" and what's the alterrnative? Sorry for asking so many questions :P

Anyway, I was already working on cleaning up the code (the coments actually helped me while making the script). About the sleep()s, you're right. I've also noticed that I don't like them that much and that they're unnecessarily eating up time and RAM.

But thank you very much for the feedback!

Best regards,
Luis Ferreira.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby micseydel » Mon Jun 17, 2013 1:17 pm

PEP 8: Consistency is important. Everyone in the open source community knows it, and can read your code much faster. If you're not going to use PEP 8, you should be consistent with whatever you do use (I didn't look closely at your code to see if you do this).

Repo: They're great for bragging rights, recruitment, history, version control (which you manually did here), distribution, keeping track of when others modify it. Git is just fantastic. I even use it for local scripts once they get reasonably large. It's not hard to use, and has a great deal of benefits.

If you define a function inside of a function definition, then that's called nested functions. The alternative, in your case, is to not create a function you're only going to call once anyway.
Code: Select all
    if EquationType == '1st':
        def solve1(eq,var='x'):
            eq1 = eq.replace("=","-(")+")"
            c = eval(eq1,{var:1j})
            print(-c.real/c.imag)
        eq = input('Type your equation here (use "x" as variable): ')
        solve1(eq,var='x'

becomes
Code: Select all
    if EquationType == '1st':
        eq = input('Type your equation here (use "x" as variable): ').replace("=","-(")+")"
        c = eval(eq1,{var:1j})
        print(-c.real/c.imag

in terms of the removing of the function. (I did not make any of my other suggested changes.)

Questions are good! Google whatever you can and then ask the best questions you can here.

Sleeps don't use any meaningful amount of RAM, if any at all, and don't waste CPU time either.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1354
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 2:59 pm

thank you very much for your help!

About PEP8: I'll take a look at that on google and let you know about the result :)

About nested functions: In my first version of the script, I had MANY of those - yet I tried to remove all of them. That may've escaped, I'll give a second look to that.

About the repository: that's a great idea, I'll check it right away and leave the link here.

Anyway, thank you once again :D

Best regards,
Luis Ferreira.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 3:37 pm

So, I checked the PEP's and I'm reading them (I hope to release a new version of "Equation solver" PEP8-friendly); I also checked the repository - It looks really nice and it's a useful way to keep track of my scripts (thank you for the idea :P ).

About the nested function that you showed to me... The one you made didn't work for me. I can't see what's the problem, I think it should be working fine. Anyway, I'll try to make more things like that and make my code more beautiful - AND better :D
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby micseydel » Mon Jun 17, 2013 3:47 pm

Replace the variable "var" with the string "x". I wrote it twice, and did it right the first time but forgot about it the second time.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1354
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 4:11 pm

ok, thank you!
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 4:22 pm

Well, looks like I forgot to add some things - e.g.: when you type a letter instead of a number to give a value to "a", the app crashes.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby micseydel » Mon Jun 17, 2013 4:25 pm

You should post your current code, the input and output, and the full traceback that you get. I like the traceback in code tags since it often has indentation too.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1354
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 4:43 pm

Currently, it's like this:
Code: Select all
print('''Welcome to:

+--------------------+
|EQUATION SOLVER V0.3|
+--------------------+

by: Luís Ferreira
''')

import math
import time

def continue1choice():
    continue1 = input('Do you want to solve more equations? (y/n) ')
    if continue1 == 'y':
        EquationSolver()
    elif continue1 == 'n':
        print('Thank you for checking my app!')
    elif continue1 != 'y' and continue1 != 'n':
        print('You must chose "y" (yes) or "n" (no)!')
        continue1choice()

def EquationSolver():
    EquationType = input('Equations degree (1st or 2nd): ')
    if EquationType == '1st':
        eq = input('Type your equation here (use "x" as variable): ').replace("=","-(")+")"
        c = eval(eq,{'x':1j})
        print(-c.real/c.imag)
        continue1choice()
    elif EquationType == '2nd':
        solve2()
        continue1choice()


def solve2():
    print('Your equation is, in the canonical form: a*x^2 + b*x + c = 0')
    a = int(input('Assign a value to "a": '))
    b = int(input('Assign a value to "b": '))
    c = int(input('Assign a value to "c": '))
    delta = b**2 - 4*a*c
    if delta < 0:
        print('The equation is impossible - it has 0 solutions.')
        continue1choice()
    elif a == 0 and b == 0:
        print('The equation is impossible - it has 0 solutions.')
        continue1choice()
    elif delta == 0:
        x = -b
        print('Your equation has 1 solution, which is %r.' % r)
        continue1choice()
    elif delta > 0:
        pass
    sqrtDelta = math.sqrt(delta)
    x1 = (-b + sqrtDelta)/2*a
    x2 = (-b - sqrtDelta)/2*a
    print('Your equation has 2 solutions, which are %r and %r.' %(x1, x2))

def MainMenu():
    print('- MAIN MENU -')
    print('What do you want to do?')
    print('''[1] Start solving equations
[2] More info
[3] Quit''')
    option1 = input(':: ')
    if option1 == '1':
        EquationSolver()
    elif option1 == '2':
        print('''- More info -
This small app, Equation Solver, was totally made by me,
Luís Ferreira, in order to use it for educational purpo-
ses for me (to start working better with Python) and for
others too, as a suplement to their education in Math. I
hope that you comprehend that there maybe many mistakes
with the code, since I'm relativly new to Python and sin-
ce this project is still in a very fresh fase. However,
I don't want to make this like Sympy or other equation
solvers - although I used some useful tips and code avai-
lable on the internet. I hope you enjoy it and let me know
about any mistakes or sugestions.
Thank you for trying it!''')
        input('Press [enter] to continue')
        print('')
        MainMenu()
    elif option1 == '3':
        print('Thank you for checking my app!')
        time.sleep(3)
    elif option1 != '1' and option1 != '2' and option1 != '3':
        print('You must chose an available option!')
        MainMenu()

MainMenu()


However, when I give, for example, the value "a" to "a", while solving a 2nd degree equation, it gives me this error:

Code: Select all
Welcome to:

+--------------------+
|EQUATION SOLVER V0.3|
+--------------------+

by: Luís Ferreira

- MAIN MENU -
What do you want to do?
[1] Start solving equations
[2] More info
[3] Quit
:: 1
Equations degree (1st or 2nd): 1st
Type your equation here (use "x" as variable): 23*x=0
-0.0
Do you want to solve more equations? (y/n) y
Equations degree (1st or 2nd): 2nd
Your equation is, in the canonical form: a*x^2 + b*x + c = 0
Assign a value to "a": a
Traceback (most recent call last):
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 91, in <module>
    MainMenu()
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 66, in MainMenu
    EquationSolver()
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 29, in EquationSolver
    continue1choice()
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 16, in continue1choice
    EquationSolver()
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 31, in EquationSolver
    solve2()
  File "L:\Portable Python 3.2.5.1\My scripts\Equation Solver v0-3.py", line 37, in solve2
    a = int(input('Assign a value to "a": '))
ValueError: invalid literal for int() with base 10: 'a'


to solve this, I guess I could do the following to all the places where this could happen:
Code: Select all
def solve2():
    print('Your equation is, in the canonical form: a*x^2 + b*x + c = 0')
    a = input('Assign a value to "a": ')
    try:
        int(a)
        return True
    except ValueError


I haven't tried this yet, so I don't know if this works. i'll just try some times and check it
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 4:46 pm

Here it is, problem solved (I guess):

Code: Select all
def solve2():
    print('Your equation is, in the canonical form: a*x^2 + b*x + c = 0')
    a = input('Assign a value to "a": ')
    try:
        int(a)
        pass
    except ValueError:
        print('You must type only numbers and math symbols!')
        EquationSolver()
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby micseydel » Mon Jun 17, 2013 4:52 pm

The best way to do this is to totally separate the user interaction from the logic which solves the problem. You should validate the input before passing it as (an) argument(s) to the function, and then the function should return the solution rather than print it, and shouldn't re-prompt the user for anything more.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1354
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 5:00 pm

So, you're telling me to first ask the user to give me the values for,let's say, a,b and c, and then turn them into integers? Anyway, this now works, although it makes the code a bit long. I'll check if I can reduce it without getting it too complex.

Another point of interest is about trying to to the same thing, but with 1st degree equations. Since it asks at once for the entire equation, it'll be hard to detect any error, I guess. we could try doing like this:

if 'a' in eq or 'b' in eq or 'c' in eq (...) or 'z' in eq

but i highly doubt that this would be efficient or even work. well, these are the dillemas of coding xD

I'll try to get a away through that.
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm

Re: Equation Solver

Postby luis.simao.af98 » Mon Jun 17, 2013 5:55 pm

Hey, I found a way to solve the crashing problem in the 1st degree equations, using also a "try and exception" thing. If you didn't write an equation in the correct way, the app would crash, but now the problem is solved. Here it is:

Code: Select all
def EquationSolver():
    EquationType = input('Equations degree (1st or 2nd): ')
    if EquationType == '1st':
        eq = input('Type your equation here (use "x" as variable): ')
        try:
            eq1 = eq.replace("=","-(")+")"
            c = eval(eq1,{'x':1j})
            pass
        except SyntaxError:
            print('You must write a vallid equation!')
            EquationSolver()
        eq1 = eq.replace("=","-(")+")"
        c = eval(eq1,{'x':1j})
        print(-c.real/c.imag)
luis.simao.af98
 
Posts: 18
Joined: Thu May 16, 2013 8:37 pm


Return to Completed Scripts

Who is online

Users browsing this forum: No registered users and 1 guest

cron