单调性 相关性 鲁棒性python代码
时间: 2023-10-12 22:45:18 浏览: 59
请问您想要了解单调性、相关性和鲁棒性的Python代码吗?如果是的话,我可以为您提供一些示例代码。以下是针对这些概念的Python代码示例:
1. 单调性的判断:
```python
def is_monotonic(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1)) or all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))
# 使用示例
nums = [1, 2, 3, 4, 5]
print(is_monotonic(nums)) # 输出:True
nums = [5, 4, 3, 2, 1]
print(is_monotonic(nums)) # 输出:True
nums = [1, 3, 2, 4, 5]
print(is_monotonic(nums)) # 输出:False
```
2. 相关性的计算(使用Pearson相关系数):
```python
import numpy as np
def correlation(x, y):
return np.corrcoef(x, y)[0, 1]
# 使用示例
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
print(correlation(x, y)) # 输出:1.0
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
print(correlation(x, y)) # 输出:-1.0
x = [1, 2, 3, 4, 5]
y = [1, 1, 1, 1, 1]
print(correlation(x, y)) # 输出:0.0
```
3. 鲁棒性的示例:
```python
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
result = "除数不能为零!"
except Exception as e:
result = str(e)
return result
# 使用示例
print(divide(10, 2)) # 输出:5.0
print(divide(10, 0)) # 输出:"除数不能为零!"
print(divide(10, 'a')) # 输出:"unsupported operand type(s) for /: 'int' and 'str'"
```
以上是关于单调性、相关性和鲁棒性的Python代码示例,希望对您有帮助!如果您还有其他问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)