Effective Python - 函数

Effective Python - 函数

14.尽量用异常来表示特殊情况,而不要返回None

(1)如果令函数返回None来表示一些特殊意义,调用者很容易写出错误的代码,因为None,0,空字符串,空列表一类值,在条件表达式中会被判定为False。

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        return None

res1 = divide(0, 3)
res2 = divide(3, 0)

if not res1:
    print('invalid input') #invalid input

if not res2:
    print('invalid input') #invalid input

说明:我们一般不会去判定函数的返回值是否为None,而是去假定:只要函数返回了与False等效的运算结果,就说明函数出错。

 

(2)函数在遇到特殊情况下应抛出异常,并在函数文档中添加相应的描述,不应返回None;

 调用者在看到函数文档中关于异常的描述后,会编写相应的代码来处理它们。

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError as e:
        raise ValueError('invalid inputs') from e

说明:不返回None,而是把异常抛给上一级,使调用者必须应对它;

将ZeroDivisionError转化成ValueError用以表示调用者输入的值是无效的。

 

还有一种方法:把返回值拆成两部分放到元组里

def divide(x, y):
    try:
        return True, x / y
    except ZeroDivisionError:
        return False, None

success, res = divide(3, 0)
if not success:
    print('invalid input') #invalid input

但是这种方法存在一个问题,调用者可以通过下划线为名称的变量跳过元组的第一部分。

(python习惯用下划线来表示用不到的变量)

这和直接返回None有着相同的错误,所以并不推荐这种写法。

_, res = divide(0, 3)
if not res:
    print('invalid input') #invalid input

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CMA-ES(Covariance Matrix Adaptation Evolution Strategy)是一种基于进化算法的优化方法,用于寻找非线性、高维、非凸函数的最优解。下面是Python实现CMA-ES的示例代码: ```python import numpy as np from scipy.stats import multivariate_normal class CMAES: def __init__(self, dim, mu, sigma): self.dim = dim self.mu = mu self.sigma = sigma self.lambda_ = int(4 + np.floor(3 * np.log(dim))) # population size self.weights = np.log(self.lambda_ + 1 / 2) - np.log(np.arange(1, self.lambda_ + 1)) self.weights /= np.sum(self.weights) self.mu_eff = np.sum(self.weights) ** 2 / np.sum(self.weights ** 2) # variance-effective size of mu self.c_sigma = (self.mu_eff + 2) / (dim + self.mu_eff + 5) # learning rate for sigma control self.d_sigma = 1 + 2 * max(0, np.sqrt((self.mu_eff - 1) / (dim + 1)) - 1) + self.c_sigma # damping parameter for sigma control self.pc = np.zeros(dim) # evolution path for C self.ps = np.zeros(dim) # evolution path for sigma self.B = np.eye(dim) # transformation matrix self.D = np.ones(dim) # diagonal matrix self.C = np.eye(dim) # covariance matrix self.sigma_hist = [] def ask(self): self.z = np.random.randn(self.lambda_, self.dim) self.y = np.dot(self.z, self.B * np.diag(self.D)) * self.sigma + self.mu return self.y def tell(self, x, fit): idx = np.argsort(fit) z = np.dot(self.B.T, self.z[idx, :].T).T / np.sqrt(self.D) self.pc = (1 - self.c_sigma) * self.pc + np.sqrt(self.c_sigma * (2 - self.c_sigma) * self.mu_eff) * np.sum(self.weights[:, None] * z[:self.mu, :], axis=0) self.ps = (1 - self.c_sigma) * self.ps + np.sqrt(self.c_sigma * (2 - self.c_sigma)) * np.dot(self.B, np.dot(np.diag(1 / np.sqrt(self.D)), np.mean(z[:self.mu, :], axis=0))) hsig = np.linalg.norm(self.ps) / np.sqrt(1 - (1 - self.c_sigma) ** (2 * self.iteration)) / self.d_sigma < 1.4 + 2 / (self.dim + 1) self.sigma *= np.exp((self.c_sigma / self.d_sigma) * (np.linalg.norm(self.ps) / self.sigma - 1)) if hsig: self.C = (1 - self.c_sigma) * self.C + self.c_sigma * np.dot(self.pc[:, None], self.pc[None, :]) + self.c_sigma * (1 - np.sum(self.weights ** 2)) * self.C else: self.C = (1 - self.c_sigma) * self.C + self.c_sigma * np.dot(self.pc[:, None], self.pc[None, :]) self.D, self.B = np.linalg.eigh(self.C) self.D = np.sqrt(self.D) self.sigma_hist.append(self.sigma) self.iteration += 1 def result(self): return self.mu, self.sigma, self.sigma_hist ``` 使用示例: ```python def sphere(x): return np.sum(x ** 2) es = CMAES(dim=10, mu=5, sigma=1) for i in range(100): x = es.ask() fit = np.array([sphere(x[i]) for i in range(len(x))]) es.tell(x, fit) print(es.result()) ``` 此示例演示了使用CMA-ES来优化10维球函数的最小值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值