Search code examples
pythonpython-2.7calculatorsubtraction

Subtract each value of a list Python


I'm trying to build a simple calculator. I have done the addition part using sum function. However, I'm not able to achieve the same with subtraction. I want to subtract each value in the list from the value before it, i.e., if the list (user input) is [10,5,3], I want my output to be 10-5-3=2. Here's my code so far.

def calculate():
    input = raw_input("input: ")
    if "+" in input:
        sum_val = sum(map(float, input.split('+')))
        if sum_val.is_integer():
            print int(sum_val)
        else:
            print sum_val
    elif "-" in input:
        print map(float, input.split('-'))

calculate()

User input can be 10-5-3.


Solution

  • l = [10,5,3]    
    s = reduce(lambda x, y: x - y, l)
    

    s == 2