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
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...
[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....
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...
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:...
This is C programming assignment. The objective of this homework is to give you practice using...
This is C programming assignment. The objective of this homework is to give you practice using make files to compose an executable file from a set of source files and adding additional functions to an existing set of code. This assignment will give you an appreciation for the ease with which well designed software can be extended. For this assignment, you will use both the static and dynamic assignment versions of the matrix software. Using each version, do the following:...
Below are three different codes in Matlab, please copy those your matlab and answer the following...
Below are three different codes in Matlab, please copy those your matlab and answer the following questions: Thank you for your help!!!! 1.1 Baseband Signal a) Plot time versus baseband signal (m_sig). b) Plot freq versus baseband signal spectrum (M_fre). 1.2 Amplitude Modulation – Suppressed Carrier. a) Plot time versus the DSB-SC signal (s_dsb). b) Plot freq versus the DSB-SC signal spectrum (S_dsb). 1.3 Coherent Demodulation a) Plot freq versus the pre-filtered signal (S_dem). b) Plot freq versus the post-filtered...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
What is a Capital Asset?, Holding Period, Calculation of Gain or Loss, Net Capital Losses (LO...
What is a Capital Asset?, Holding Period, Calculation of Gain or Loss, Net Capital Losses (LO 8.1, 8.2, 8.3, 8.5) Charu Khanna received a Form 1099-B showing the following stock transactions and basis during 2016: Stock Date Purchased Date Sold Sales Price Cost Basis 4,000 shares Green Co. 06/04/05 08/05/16 $12,000 $3,000 500 shares Gold Co. 02/12/16 09/05/16 54,000 62,000 5,000 shares Blue Co. 02/04/06 10/08/16 18,000 22,000 100 shares Orange Co. 11/15/15 07/12/16 19,000 18,000 None of the stock...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT