python - 结构模式匹配和无穷大

标签 python structural-pattern-matching

我正在计算非负pLp距离函数。对于除 p = 0 和 p = ∞ 之外的所有情况,内置的 pow() 函数都可以很好地发挥作用。 在了解结构模式匹配之前,我使用过字典和异常处理:

from math import sqrt, inf
distance_function = {   0.0: lambda x, y: int(x != 0.0) + int(y != 0.0),
                        1.0: lambda x, y: abs(x) + abs(y), # Likely a tad faster than 'pow()'       
                        inf: lambda x, y: max(abs(x), abs(y))}                  
def lp_distance(x, y, p): 
    try:                return distance_function[p](x, y)                   
    except KeyError:    return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)

有些人不希望这里有异常(exception)。所以我将代码片段重写为以下代码:

def lp_distance(x, y, p):
    match p:
        case 0.0:           return int(x != 0.0) + int(y != 0.0)
        case 1.0:           return abs(x) + abs(y)      
        # The line below triggers "SyntaxError: name capture 'inf' makes remaining patterns unreachable"
        case inf:           return max(abs(x), abs(y))
        # But the following works:
        case p if p == inf: return max(abs(x), abs(y))
        case _:             return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)

为什么 case inf: 不正确(Python v3.10.2)?

最佳答案

case声明,a simple name is a pattern that captures (assigns) to that name 。相比之下,a dotted name is a patterns that refers to the value of that name .

In simple terms NAME will always succeed and it will set NAME = <subject>.

In simple terms NAME1.NAME2 will succeed only if <subject> == NAME1.NAME2

仅使用case inf:表示要匹配的值无条件分配给名称 inf – 名称是否先前已绑定(bind)并不重要。
你想要的是 case math.inf: ,表示与该值进行比较。

import math

def lp_distance(x, y, p):
    match p:
        case 0.0:
            return int(x != 0.0) + int(y != 0.0)
        case 1.0:
            return abs(x) + abs(y)      
        # compare against a value by using its dotted name
        case math.inf:
            return max(abs(x), abs(y))
        case _:
            return pow(pow(abs(x), p) + pow(abs(y), p), 1.0/p)

关于python - 结构模式匹配和无穷大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71091850/

相关文章:

python - Tensorflow slim 训练和验证初始模型

python - 如果当前值大于现有最小值,则更新 mysql 中的表,否则忽略该更新

python - Point() 接受 0 个位置子模式(给定 2 个)

Python 结构模式匹配

python - 如何在hadoop分布式文件系统(hdfs)上执行python文件(.py)

Python - 如何连续运行脚本以在 Windows 目录中查找文件

python - 如何用结构模式匹配来表达 hasattr() 鸭子类型(duck typing)逻辑?

python - 使用结构模式匹配反转测试

python - JSON 对象中的项目使用 "json.dumps"出现故障?