【问题标题】:Using decorators to solve mathematical equations in Python (Past Paper Qs)在 Python 中使用装饰器求解数学方程(Past Paper Qs)
【发布时间】:2015-12-15 01:49:11
【问题描述】:

我被要求找到一个函数的模 37 (%37)。

确保您的函数返回 0 到 36 之间的整数。 假设所有参数都是 0 到 36 之间的整数。 写一个装饰器@normalize_37 就是这样做的。 IE。如果 'bar' 是一个函数,那么修饰函数的所有参数都会以 37 为模,其返回值以 37 为模。

查找:

@normalize_37
def add(x,y):
     return x+y
print(add(45,67))
#where the answer is 1.

@normalize_37
 def bar(n):
     if n >= 37 or n <= -1:
         raise ValueError
     else:
         return n
print(bar(123))
#where the answer is 12

到目前为止,我是从网上查找装饰器中初步想到的:

import math

def document(f):
    def wrap(x,y):
        print("I am going to find modulo 37 of", x,y)
        f(x,y)
    return wrap

@document
def add(x,y):
    print(add(x,y)%37)

add(45,67)

但它对我不起作用,当我运行它时,它只是一遍又一遍地重复“我要找到模 37 的”位。

【问题讨论】:

  • ...您调用f(x, y),但实际上并没有对其取模或返回结果。

标签: python function math decorator modulo


【解决方案1】:

请求的具体表格是

def normalize_37(fn):              # the decorator
    def inner(x, y):               # the new decorated function
        return fn(x, y) % 37
    return inner

@normalize_37
def add(x, y):
    return x + y

add(45, 67)    # returns 112 % 37 == 1

但我们可以进一步概括,

def normalize(n):                  # make a decorator!
    def decorator(fn):             # the decorator
        def inner(*args):          # the new decorated function
            return fn(*args) % n
        return inner
    return decorator

@normalize(37)
def add(*args):
    return sum(args)

add(45, 67)    # returns 112 % 37 == 1

编辑: 好的,我也错过了减少参数的部分。于是就变成了

def normalize(n):                  # make a decorator!
    def decorator(fn):             # the decorator
        def inner(*args):          # the new decorated function
            return fn(*(arg % n for arg in args)) % n
        return inner
    return decorator

@normalize(37)
def add(*args):
    return sum(args)

add(45, 67)    # returns ((45 % 37) + (67 % 37)) % 37 == 1

或更简单的形式,

def normalize_37(fn):              # the decorator
    def inner(x, y):               # the new decorated function
        return fn(x % 37, y % 37) % 37
    return inner

【讨论】:

  • 好吧,看看他的bar例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多