Question

Let s be a string that contains a simple mathematical expression, e.g., s = '1.5 +...

Let s be a string that contains a simple mathematical expression, e.g.,

s = '1.5 + 2.1-3'

s = '10.0-1.6 + 3 - 1.4'

The expression will have multiple operands. We don't know exactly how many operands there are in s.

The operator will be one of the following: +, -.

Write a function called plus_minus() that takes s as the input, interpret the expression, then evaluate and return the output.

Note: The use of the eval() is not allowed in this exercise. Even if you do pass all the test cases, if you use eval() in your code, you will receive a grade of 0 for this question!

My codes below here:

def plus_minus(s):
# enter your code below this line
num_list = []
operator = []
temp = ''
  
for i in s:
if i not in ['+', '-']:
temp = temp + i
else:
num_list.append(temp)
temp = ''
operator.append(i)
num_list.append(temp)
result=float(num_list[0])
  
for i in range(0,len(operator)):
if operator[i]=='+':
result+=float(num_list[i+1])
elif operator[i]=='-':
result-=float(num_list[i+1])
  
  
return result

It works when s = '1.5 + 2.1-3' and s = '10.0-1.6 + 3 - 1.4', but it doesn't work when s='-1.5+2.1-3'

Homework Answers

Answer #1

I have solved the problem please go through the comments.

First collecting numbers and operators differently is first later we will convert the number list strings to float values.

The case when '-' comes first should be handled separately and in any case if somebody enter '+' at start that case as well is handled.

def plus_minus(s):
# enter your code below this line
    num_list = [] # list for collecting numbers
    operator = [] # list for collecting operators
    temp = '' # empty string
    for i in s: # looping for string
        # till + or - are seen we combine each number to a 
        # single string like so that 1.5 200 numbers form a single string
        if i not in ['+', '-']: 
            temp = temp + i
        else: # when + or - are seen we add the exisiting temp string to numbers list and make the string empty
            num_list.append(temp.strip())
            temp = ''
            operator.append(i)
    num_list.append(temp) # the final number is attached not attached to num_list becase for loops ends before appending
    # print(operator)
    # print(num_list)
    if num_list[0] == '': # this happend only when string starts with a '-' or '+' operator
        num_list.pop(0) # we pop the first empty space in number list because of '-' or '+' 
        # if the operator is - we multiply -1 with the first number and pop the first operator is opertor list as well
        if operator[0] == '-': 
            operator.pop(0)
            num_list[0] = -1 * float(num_list[0])
        else:
            operator.pop(0)
            num_list[0] = float(num_list[0])
            
        for i in range(1,len(num_list)): # making rest of the elements of list to float objects
            num_list[i] = float(num_list[i])
    # if there is no '' empty string at starting of num list there is no operator at 
    # starting so convert all the elements to float without any problem
    else: 
        for i in range(len(num_list)):
            num_list[i] = float(num_list[i])
    
    # print(num_list)
    result = num_list[0] # result will be initiated with numlist[0] value and add the rest as per the operators
    for i in range(len(operator)):
        if operator[i] == '+':
            result += num_list[i+1]
        if operator[i] == '-':
            result -= num_list[i+1]
    return result
plus_minus('-5+2+6-8')

Image Snippets of code and output:

Output for different Examples:

If you want to round the 2 decimal points just write round(result,2) in the code in place result while returning from the function.

Drop a comment for any further doubts.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will...
Program will allow anywhere between 1 and 6 players (inclusive). Here is what your output will look like: Enter number of players: 2 Player 1: 7S 5D - 12 points Player 2: 4H JC - 14 points Dealer: 10D Player 1, do you want to hit? [y / n]: y Player 1: 7S 5D 8H - 20 points Player 1, do you want to hit? [y / n]: n Player 2, do you want to hit? [y / n]: y...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5,...
Python 3 Rewrite KNN sample code using KNeighborsClassifier . ● Repeat KNN Step 1 – 5, for at least five times and calculate average accuracy to be your result. ● If you use the latest version of scikit -learn, you need to program with Python >= 3.5. ● Use the same dataset: “ iris.data ” ● Split your data: 67% for training and 33% for testing ● Draw a line chart: Use a “for loop” to change k from 1...
[PART ONE OF PROJECT, ALREADY COMPLETED] An accumulator is a primitive kind of calculator that can...
[PART ONE OF PROJECT, ALREADY COMPLETED] An accumulator is a primitive kind of calculator that can evaluate arithmetic expressions. In fact, the Arithmetic-Logic Unit (ALU) of the rst computers was just an accumulator. An arithmetic expression, as you know, consists of two kinds of tokens: operands and operators All our operands will be (float) numbers and for a start, we shall use only two operators: + (plus) and - (minus) A sample run of the program would look like this....
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of...
"""Prep 7 Synthesize === CSC148 Fall 2020 === Department of Mathematical and Computational Sciences, University of Toronto Mississauga === Module Description === Your task in this prep is to implement each of the unimplemented Tree methods in this file. The starter code has a recursive template that includes the "size-one" case; you may or may not choose to use this in your final implementations. """ from __future__ import annotations from typing import Any, List, Optional class Tree: """A recursive tree...
Write a program that reads a binary string (string of 0’s and 1’s) converting the binary...
Write a program that reads a binary string (string of 0’s and 1’s) converting the binary value into decimal. Allow the user to type in as many numbers as they want (one at a time) and end the program when they type in “0”. Use Horner’s method (given in step 3, below) to convert from binary to decimal. Sample Run Binary to Decimal Conversion Enter a binary string: 1101 1101 = 13 decimal Enter a binary string: 10011001 10011001 =...
Develop a Traceroute application in python using ICMP. Your application will use ICMP but, in order...
Develop a Traceroute application in python using ICMP. Your application will use ICMP but, in order to keep it simple, will not exactly follow the official specification in RFC 1739.. Below you will find the skeleton code for the client. You are to complete the skeleton code. The places where you need to fill in code are marked with #Fill in start and #Fill in end. Code from socket import * import os import sys import struct import time import...
For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from...
For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from a file. Specifically, you will implement the following function: /* * Reads one arithmetic "expression" at a time from a file stream, computes, then * returns the result. If there are additional expressions in the file, they are * read and computed by successive calls to “calculator”. * * “Expressions” are groups of operations (add, subtract, multiply, divide). Your * calculator will read and...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix...
Data Structure in C++ I keep getting the same warning, and I cant seem to fix it.. Can you explain to me what I am doing wrong? Warning: dlist.cc: In function 'std::ostream& operator<<(std::ostream&, dlist&)': dlist.cc:66:10: error: invalid initialization of reference of type 'std::ostream& {aka std::basic_ostream&}' from expression of type 'dlist::node*' dlist.cc: In function 'dlist operator+(dlist&, dlist&)': dlist.cc:93:8: error: invalid operands of types 'dlist::node*' and 'dlist::node*' to binary 'operator+' dlist.cc:97:8: error: could not convert 'result' from 'int' to 'dlist' My code:...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT