7
\$\begingroup\$

This code defines a function to solve two-step linear equations of the form coefficient * variable + constant = solution. It prompts the user for the coefficient, variable, constant, and solution, validating that each input is numeric (except the variable, which must be a letter). If the constant is negative, it formats the equation without a "+" sign. The function solves for the variable and handles special cases like a zero coefficient (displaying "Undefined" in such cases). The helper function check_int(x) ensures that integer values are returned as integers, not floats.

With all of this said, I would like to improve the efficiency of this code. Do you have any suggestions?

def check_int(x):
 if x.is_integer():
 return int(x) # Return the integer version of x if it's an integer
 return x
def two_step_equations_one():
 try:
 coefficient = float(input("Coefficient: "))
 coefficient = check_int(coefficient) # Correctly update the coefficient
 print(f"{coefficient}x + x = x")
 except ValueError:
 print("Cannot input letters as coefficient.")
 return # Exit the function if an invalid coefficient is entered
 
 variable = input("Variable: ")
 while not variable[0].isalpha(): # Check if the first character is a letter
 variable = input("Variable must be a letter. Try again: ")
 print(f"{coefficient}{variable} + x = x")
 
 try:
 constant = float(input("Constant: "))
 constant = check_int(constant) # Correctly update the constant
 
 # Print the equation with or without the '+' based on whether the constant is negative
 if constant < 0:
 print(f"{coefficient}{variable} {constant} = x") # No '+' if constant is negative
 else:
 print(f"{coefficient}{variable} + {constant} = x") # Include '+' if constant is positive
 
 except ValueError:
 print("Cannot input letters as constant.")
 return # Exit the function if an invalid constant is entered
 
 try:
 solution = float(input("Solution: "))
 solution = check_int(solution) # Correctly update the solution
 if constant < 0:
 print(f"{coefficient}{variable} {constant} = {solution}") # No '+' if constant is negative
 else:
 print(f"{coefficient}{variable} + {constant} = {solution}") # Include '+' if constant is positive
 except ValueError:
 print("Cannot input letters as solution.")
 return # Exit the function if an invalid solution is entered
 
 if coefficient > 0:
 answer = (solution - constant) / coefficient
 answer = check_int(answer) # Check if answer is an integer
 print(f"{variable} = {answer}")
 
 elif coefficient < 0:
 answer = (solution + constant) / coefficient
 answer = check_int(answer) # Check if answer is an integer
 print(f"{variable} = {answer}")
 # Handle case when the coefficient is zero
 else:
 print(f"{variable} = Undefined")
two_step_equations_one()
toolic
14.4k5 gold badges29 silver badges201 bronze badges
asked Jan 29 at 19:31
\$\endgroup\$
0

2 Answers 2

7
\$\begingroup\$

Things I like: you have functions, you have some validation, and the code basically works.

I think it's too complicated, and I think it tries to do too much. I don't think the features to get the variable name or re-print the equation are useful. I suggest instead printing a fixed-format equation, prompting for each of the three knowns, and then printing the solution.

I also suggest using Fraction, because it has good support for conversion of integers, fractions and real numbers from strings; and it can do this math and show a lossless result.

Your incremental prints like this:

print(f"{coefficient}x + x = x")

are confusing and incorrect, because I would always interpret those x letters literally and that would lead me to believe that the coefficient must only ever equal zero for this equation to be true.

I suggest instead something like

from fractions import Fraction
def input_frac(name: str) -> Fraction:
 while True:
 try:
 return Fraction(input(name + ' = '))
 except ValueError as e:
 print(str(e))
def solve() -> None:
 print('ax + b = c')
 a = input_frac('a')
 b = input_frac('b')
 c = input_frac('c')
 print('x =', (c - b)/a)
if __name__ == '__main__':
 solve()
ax + b = c
a = 4/3
b = 2.2
c = 1
x = -9/10
answered Jan 30 at 0:04
\$\endgroup\$
1
  • \$\begingroup\$ i fixed this part of the code to make more sense "print(f"{coefficient}x + x = x")" to be "print(f"{coefficient}_ + _ = _") \$\endgroup\$ Commented Jan 31 at 15:44
4
\$\begingroup\$

UX

When I run the code, I'm not sure what to do at each user prompt. It would be helpful to display some introductory instructions before prompting the user for input. I recommend showing example input for each of the prompts:

 Coefficient: 
 Variable: 
 Constant: 
 Solution: 

Comments

Many of the comments in the code are not needed because they merely restate what the code is obviously doing. Here are a couple of examples:

answer = check_int(answer) # Check if answer is an integer
return int(x) # Return the integer version of x if it's an integer

Documentation

The PEP 8 style guide recommends adding a docstring for each function.

For the check_int function, it would be useful to know exactly what you are checking. The docstring could explicitly state what the input is expected to be (a floating-point numeric value, if that is the case). It could also state that it converts it to an int type, and why it is important to do the conversion:

def check_int(x):
 """
 The input is expected to be a floating-point number.
 If it is an integer, then return an `int` type because...
 Otherwise, just return it as a float.
 """

Naming

Since you use x as a variable in your equations, it might be a little misleading to use x as the check_int function input parameter as well. Perhaps a better variable name in the function would be number:

def check_int(number):
answered Jan 30 at 12:37
\$\endgroup\$

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.