Home > OS >  I wanna make a function of 1 variable which is a string.(number1 mathematical operation( - * / ) nu
I wanna make a function of 1 variable which is a string.(number1 mathematical operation( - * / ) nu

Time:07-16

def calculate_from_string('string'):

#I tried doing a lot of things that didnt work out for me and I cant use the eval function in this code.

CodePudding user response:

OPERATIONS = {
    " ":lambda x,y:x y,
    "*":lambda x,y:x*y,
    "-":lambda x,y:x-y,
    "/":lambda x,y:x/y
}

def calculate(string):
    global OPERATIONS
    import re # regular expresion module
    # "8   8" is the same as "8 8"
    # but "-8 * 8" is not "- 8 * 8" so be careful
    pattern = re.findall(r"(-?\d)[ \t]*(.)[ \t]*(-?\d)",string)
    # pattern will be: [(number1, symbole, number2)]
    # or an empty list if no patterns was found in string
    if bool(pattern): # test if the list contain at least somthing with bool()
        nb1 = int(pattern[0][0])
        nb2 = int(pattern[0][2])
        sym = pattern[0][1]
        if sym in OPERATIONS:
            return OPERATIONS[sym](nb1,nb2)
        else:
            return "operation do not contain "   sym

print(calculate("8*-8"))
print(calculate("8/-8"))
print(calculate("8^-8"))
print(calculate("8--8"))

a not so easy, but extensible way to do it is with the regex (re) module

the r"(-?\d)[ \t]*(.)[ \t]*(-?\d)" can manage negative numbers

CodePudding user response:

You can first check which operator is used.

def calculate_from_string(value):
    # In case of the plus
    if " " in value:
        # Split by this operator so u can get the numbers.
        numbers = value.split(" ")
        # Do your logic
        return int(numbers[0])   int(numbers[1])

CodePudding user response:

This code does a -*/b but does not works for a*-b. That would require regular expressions.

def plus(a,b):
    return a b

def minus(a,b):
    return a-b

def product(a,b):
    return a*b

def divide(a,b):
    return a/b

operate={' ':plus,'-':minus,'*':product,'/':divide}

def calculate_from_string(value):
    operators = [' ', '-', '*', '/']
    operator=[op for op in operators if op in value]
    nums=[float(n) for n in value.split(operator[0])]
    answer= operate[operator[0]](nums[0],nums[1])
    
    print(f"{nums[0]} {operator[0]} {nums[1]} = {answer}")
    return answer
    
calculate_from_string('2 3')
calculate_from_string('2-3')
calculate_from_string('2*3')
calculate_from_string('2/3')
>>> 2.0   3.0 = 5.0
>>> 2.0 - 3.0 = -1.0
>>> 2.0 * 3.0 = 6.0
>>> 2.0 / 3.0 = 0.6666666666666666

CodePudding user response:

You could use a regular expression to match the arithmetic expression string, e.g. the regex (\-?[0-9] )([\ \-\*/])(\-?[0-9] ) matches two-operand operations with operands , -, *, /, also supporting negative numbers as operands, like

  • 41 1
  • 43 -1
  • -1 43
  • 84/2
  • ...

Consider the following (incomplete) example:

import re

def calc(expr: str) -> int:
    match = re.match('(\-?[0-9] )([\ \-\*/])(\-?[0-9] )', expr)
    operand1 = int(match.group(1))
    operator = match.group(2)
    operand2 = int(match.group(3))
    
    if (operator == ' '):
        return operand1   operand2
    elif (operator == '-'):
        return operand1 - operand2
    elif (operator == '*'):
        return operand1 * operand2
    elif (operator == '/'):
        return operand1 / operand2
    else:
        raise 'Invalid operator: '   operator


print(calc('41 1'))
print(calc('43 -1'))
  • Related