Home > database >  Why am I getting different outputs for a similar input?
Why am I getting different outputs for a similar input?

Time:01-15

I am trying to solve the "Math Interptreter" problem of problem set 1 of harvard cs50 python course. The question is: In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place. Assume that the user’s input will be formatted as x y z, with one space between x and y and one space between y and z, wherein:

x is an integer y is , -, *, or / z is an integer For instance, if the user inputs 1 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.

I did the following:

expression=input("Enter the expression: ").replace(" ","")
if " " in expression:
    operation=" "
elif "-" in expression:
    operation="-"
elif "*" in expression:
    operation="*"
else:
    operation="/"
position=expression.find(operation)
x=int(expression[:position])
y=int(expression[position:])
print(x)
print(operation)
print(y)

 here

I tried to remove the spaces and then check which operation is given by the user. Then, I tried to find the position of the operation using the find keyword in order to slice the string into two parts i.e. x (which will contain the fisrt integer) and y (which will contain the second integer). Then I was about to perform the operation. But, the error is that when I enter '55 6' as an input, x is assigned as 55 and y is assigned as 6. However, when I enter '55 - 6' as an input, x is assigned as 55 and y is assigned as -6. Why is y assigned as -6?

CodePudding user response:

when you are finding x and y you need to skip the operator

x=int(expression[:position])
y=int(expression[position 1:]) # I changed position to position 1

for 55-6 earlier position was 2 and it started parsing for y starting at - symbol, when you do position 1 for y it will start with the number

CodePudding user response:

OP, you received great advice on how to fix your current design that will get you back on track. As you gain more experience in Python, however, often times you will find that the standard library can simplify tasks like these. In this case, the operator library allows you to remove a level of complexity from your code that would otherwise be error prone. Here is an example:

import operator

ops = {
    " ": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv
}
x, y, z = input("Enter equation: ").split()
print(f"{ops[y](int(x), int(z)):.1f}")

Output:

Enter equation:  3   5
8.0
  • Related