gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:19:18 25 4
gpt4 key购买 nike

我正在计算非负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/

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