gpt4 book ai didi

python - 使用装饰器在 Python 中求解数学方程(Past Paper Qs)

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:50 25 4
gpt4 key购买 nike

有人要求我求一个函数的模 37 (%37)。

Ensure that your function returns an integer between 0 and 36. Assume that all arguments are integers between 0 and 36. Write a decorator @normalize_37 that does just that. I.e. if 'bar' is a function, then the decorated function will have all its arguments reduced modulo 37 and its return value reduced modulo 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”位。

最佳答案

请求的具体表格是

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

关于python - 使用装饰器在 Python 中求解数学方程(Past Paper Qs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com