简体   繁体   中英

Is there a built-in “deviation”-function in python?

I don't know the proper terminology for this, so please correct me if the term "deviation" is wrong for what I'm talking about, but I am wondering if there is a built-in function to deviate a value using standard mathematical operators in Python that works by passing it an original value, an operand and a modification value.

I would need this to specify a "deviation" at the top layer of a program which is later applied to a value that is dynamically retrieved.

What I currently have is a function like this:

def deviateValue(value, deviation):
    value = float(value)
    operand = deviation[0]
    modifier = float(deviation[1:])
    if operand == "+":
        value += modifier
    elif operand == "-":
        value -= modifier
    elif operand == "*":
        value *= modifier
    elif operand == "/":
        value /= modifier
    elif operand == "=":
        value = modifier
    else:
        logger.warning("WARNING: Operand not implemented:", operand)
        return False

    return value

...which works, but it sort of feels like something basic like this should already implemented somewhere in the base package.

So to sum up the question: Does a function like this already exist somewhere within the basic Python modules? At the very least, I could not find it in the math module.

Instead of a + b you can also do operator.add(a, b) . With that in mind you now only have to create a mapping from your operator strings to the according operator.* functions, and call the result:

import operator

def deviate(first, operand, second):
    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '//': operator.floordiv,
        '%': operator.mod,
    }

    return ops[operand](first, second)

# 2 + 3 = 5
deviate(2, '+', 3)
# 2 * 3 = 6
deviate(2, '*', 3)
# 10 % 3 = 1
deviate(10, '%', 3)

Why not simply evaluate a string that is generated from the three inputs like this:

original=2
operand='+'
modifier=3
eval(str(original)+operand+str(modifier))

I would not recommend this, but it will do the job:

def deviateValue(v,d):
    try:
        return eval(str(v)+d)
    except:
        logger.warning("WARNING: Could not evaluate %r %s" % (v,d))
        return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM