【问题标题】:Python Mathematical signs in function parameter?函数参数中的Python数学符号?
【发布时间】:2017-01-05 09:02:30
【问题描述】:

我想知道是否有办法将数学符号添加到函数参数中。

def math(x, y, symbol):
      answer = x 'symbol' y
      return answer

这是我的意思的一个小例子。

编辑: 这是整个问题

def code_message(str_val, str_val2, symbol1, symbol2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code < ord('Z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code > ord('z'):
                code symbol1= key
                str_val2 += str(chr(code))
            elif code > ord('A'):
                code symbol2= key
                str_val2 += str(chr(code))
            elif code < ord('a'):
                code symbol2= key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2

我需要多次调用该函数,但有时使用 +/- 表示第一个符号,有时使用 +/- 表示第二个符号

原始代码:

def code_message(str_val, str_val2):
    for char in str_val:

        while char.isalpha() == True:
            code = int(ord(char))
            if code < ord('Z'):
                code -= key
                str_val2 += str(chr(code))
            elif code > ord('z'):
                code -= key
                str_val2 += str(chr(code))
            elif code > ord('A'):
                code += key
                str_val2 += str(chr(code))
            elif code < ord('a'):
                code += key
                str_val2 += str(chr(code))
            break
        if char.isalpha() == False:
            str_val2 += char
    return str_val2

【问题讨论】:

  • 抱歉,您能详细说明一下吗
  • 你的意思是answer = x "symbol" y

标签: python function math symbols sign


【解决方案1】:

我很惊讶没有人提到eval()。看下面的例子:

def function(operator1, operator2, symbol):
    return eval(str(operator1) + symbol + str(operator2))

print(function(2, 3, '+'))      # prints: 5
print(function(2, 3, '-'))      # prints: -1

# Of course you can also "chain" operations, e.g., for 4 + 5 - 6
result = function(function(4, 5, '+'), 6, '-')
print(result)                   # prints 3

# Finally, it also works with string input for the operands so you 
# can read them directly from e.g., user input with `input()`
print(function('2', '3', '+'))  # prints: 5

【讨论】:

  • eval 是程序中不建议使用的函数。它会起作用,但不建议这样做。事实上,在我看来,eval 函数随时可能变成病毒,你甚至都不知道出了什么问题
  • @MoinuddinQuadri “权力越大,责任越大”是我对此的评论。
【解决方案2】:

您不能将运算符传递给函数,但是您可以传递在operator 库中定义的运算符函数。因此,您的功能将是:

>>> from operator import eq, add, sub
>>> def magic(left, op, right):
...     return op(left, right)
...

示例

# To Add
>>> magic(3, add, 5)
8
# To Subtract
>>> magic(3, sub, 5)
-2
# To check equality
>>> magic(3, eq, 3)
True

注意:我使用函数magic 而不是math,因为math 是默认的python 库,使用预定义的关键字不是一个好习惯。

【讨论】:

    【解决方案3】:

    使用对应的函数,来自operator模块:

    from operator import add
    def math(x, y, add):
          answer = add(x, y)
          return answer
    

    您可以将数学符号传递给函数的唯一方法是在字符串模式下传递,那么您将遇到两个问题,即评估符号和方程。因此,当您处理数字时,您最好使用适当的函数来直接完成这项工作。

    你也可以使用字典将符号映射到对应的函数:

    from operator import add, sub, mul
    mapping = {"+": add, "-":sub, "*": mul}
    def math(x, y, sym):
        try:
            f = mapping[sym]
        except KeyError:
            raise Exception("Enter a valid operator")
        else:
            answer = f(x, y)
            return answer
    

    【讨论】:

    • 如果add(x, y) = answer 出现语法错误怎么办?
    • answer = add(x,y)
    • @AnttiHaapala Just,复制过去的错误!
    【解决方案4】:

    你应该首先考虑你必须使用answer = x symbol y而不是相反。

    然后关于符号的使用,您可以将函数作为参数发送。 对于基本运算符,您可以使用operator 模块。

    例如:

    import operator
    
    def math(x, y, function):
          return function(x, y)
    
    math(4,5, operator.sub)
    

    您将在文档中找到您需要的所有其他操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      相关资源
      最近更新 更多