【发布时间】: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