Homework Help for Electrical Engineering

371 results

Electrical engineering is the design, building and maintenance of electrical control systems, machinery and equipment.

For unlimited access to Homework Help, a Homework+ subscription is required.

Hi, 

I am having some issues with some code I wrote for this problem:

“Write a function namedd calc that will evaluate a simple arithmetic expression. The input to your program will be a string of the form:
operand1 operator operand2
where operand1 and operand2 are non-negative integers and operator is a single-character operator, which is either +, -, or *. You may assume that there is a space between each operand and the operator. You may further assume that the input is a valid mathemat- ical expression, i.e. your program is not responsible for the case where the user enters gibberish.
Your function will return an integer, such that the returned value is equal to the value produced by applying the given operation to the given operands.
Sample execution:
calc("5 + 10") # 15
You may not use the split or eval functions in your solution.
Hint: the hard part here is breaking the input string into its three component. You may use the find and rfind functions to find the position of the first and last space, and then use the slice operator (that is, s[startindex:endindex]) to extract the relevant range of characters. Be careful of off-by-one errors in using the slice operator.
Hint: it’s best to test your code as you work. The first step should be to break the input string into its three components. Write a program that does that, have it print out the operator and the two operands on separate lines, and test it until you are convinced that it works. Then, modifying it to perform the desired mathematical operation should be straightforward. Test your program with several different inputs to make sure it works as you expect.”

Here is my code:

def calc(exp):

    operand1 = int(exp[:1])

    operand2 = int(exp[4:6])

    operator = exp[2:3]

    

    if(operator == "+"):

        addition = operand1+operand2

        return addition

    

    if(operator == "-"):

        subtraction = operand1-operand2

        return subtraction

    

    if(operator == "*"):

        multiplication = operand1*operand2

        return multiplication

 

print(calc("5 + 10"))

print(calc("4 - 8"))

print(calc("4 * 3"))

My code does not fully meet the criteria of this question. It only works for single digit numbers. How can I make my code work for any number? 

Like: 

“504 + 507”

”5678 + 76890” and so on? 

 

Thank you. Any help is appreciated. 

 


Start filling in the gaps now
Log in