Python 测试给定问题的所有可能输入
有没有一种快速的方法可以从一个函数和相应的参数x,y中找到最大值(float),它们都是0到100之间的整数?我是否需要使用assert函数或类似的函数来获取所有可能输入的范围Python 测试给定问题的所有可能输入,python,Python,有没有一种快速的方法可以从一个函数和相应的参数x,y中找到最大值(float),它们都是0到100之间的整数?我是否需要使用assert函数或类似的函数来获取所有可能输入的范围 def fun_A(x,y): import math if x == y: return 0 first = math.cos((y%75)*(math.pi/180)) second = math.sin((x%30)*(math.pi/180)) return
def fun_A(x,y):
import math
if x == y:
return 0
first = math.cos((y%75)*(math.pi/180))
second = math.sin((x%30)*(math.pi/180))
return (first + second) / (abs(x - y))
编写一个程序来解决这个问题相当简单:
max_result=None
max_x=0
max_y=0
对于范围(0,101)内的x:
对于范围(0,101)内的y:
结果=乐趣(x,y)
如果最大结果为无或结果>最大结果:
最大结果=结果
max_x=x
max_y=y
print(f“x={max\u x}和y={max\u y}生成了{max\u result}的最大结果)
编写一个程序来解决这个问题相当简单:
max_result=None
max_x=0
max_y=0
对于范围(0,101)内的x:
对于范围(0,101)内的y:
结果=乐趣(x,y)
如果最大结果为无或结果>最大结果:
最大结果=结果
max_x=x
max_y=y
print(f“x={max\u x}和y={max\u y}生成了{max\u result}的最大结果)
我会为tan功能执行以下操作:
from math import tan
y = 0
x = 0
for x_iteration in range(0, 101):
if tan(x_iteration) > y :
x = x_iteration
y = tan(x_iteration)
x = int(x)
y = int(y)
我会为tan功能执行以下操作:
from math import tan
y = 0
x = 0
for x_iteration in range(0, 101):
if tan(x_iteration) > y :
x = x_iteration
y = tan(x_iteration)
x = int(x)
y = int(y)
对于像这样的小问题,评估每一个可能的组合并选择最大值可能足够快。numpy库使这一点易于编写且速度相当快:
import numpy as np
def fun_A(x, y):
first = np.cos((y%75)*(np.pi/180))
second = np.sin((x%30)*(np.pi/180))
return np.where(x == y, 0, (first + second) / (abs(x - y)))
x, y = np.mgrid[0:101, 0:101]
f = fun_A(x, y)
maxindex = np.argmax(f)
print('Max =', f.flat[maxindex], ' at x =', x.flat[maxindex], 'y =', y.flat[maxindex])
输出:
Max = 1.4591796850315724 at x = 89 y = 88
注意事项:
- 我刚刚将对
的调用替换为对math
的调用np
- x和y是矩阵,允许我们在一个函数调用中计算这两个值的每个可能组合
- 对于像这样的小问题,它可能足够快,可以评估每个可能的组合并选择最大值。numpy库使这一点易于编写且速度相当快:
import numpy as np
def fun_A(x, y):
first = np.cos((y%75)*(np.pi/180))
second = np.sin((x%30)*(np.pi/180))
return np.where(x == y, 0, (first + second) / (abs(x - y)))
x, y = np.mgrid[0:101, 0:101]
f = fun_A(x, y)
maxindex = np.argmax(f)
print('Max =', f.flat[maxindex], ' at x =', x.flat[maxindex], 'y =', y.flat[maxindex])
输出:
Max = 1.4591796850315724 at x = 89 y = 88
注意事项:
- 我刚刚将对
的调用替换为对math
的调用np
- x和y是矩阵,允许我们在一个函数调用中计算这两个值的每个可能组合