gpt4 book ai didi

go - 在 Go 中找到两个整数之间的最小值的正确方法是什么?

转载 作者:IT老高 更新时间:2023-10-28 13:00:34 24 4
gpt4 key购买 nike

我在我的程序中导入了数学库,并试图通过以下方式找到三个数字中的最小值:

v1[j+1] = math.Min(v1[j]+1, math.Min(v0[j+1]+1, v0[j]+cost))

其中 v1 声明为:

t := "stackoverflow"
v1 := make([]int, len(t)+1)

但是,当我运行我的程序时,出现以下错误:

./levenshtein_distance.go:36: cannot use int(v0[j + 1] + 1) (type int) as type float64 in argument to math.Min

我觉得这很奇怪,因为我还有另一个程序要写

fmt.Println(math.Min(2,3))

并且该程序输出 2 没有提示。

所以我最终将值转换为 float64,以便 math.Min 可以工作:

v1[j+1] = math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost)))

使用这种方法,我得到了以下错误:

./levenshtein_distance.go:36: cannot use math.Min(int(v1[j] + 1), math.Min(int(v0[j + 1] + 1), int(v0[j] + cost))) (type float64) as type int in assignment

所以为了摆脱这个问题,我只是将结果转换回 int

我认为这非常低效且难以阅读:

v1[j+1] = int(math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost))))

我还写了一个小的 minInt 函数,但我认为这应该是不必要的,因为使用 math.Min 的其他程序在取整数时工作得很好,所以我得出结论,这一定是我的程序的问题,而不是库本身的问题。

我做错了什么吗?

这是一个可用于重现上述问题的程序,特别是第 36 行:主包

import (
"math"
)

func main() {
LevenshteinDistance("stackoverflow", "stackexchange")
}

func LevenshteinDistance(s string, t string) int {
if s == t {
return 0
}
if len(s) == 0 {
return len(t)
}
if len(t) == 0 {
return len(s)
}

v0 := make([]int, len(t)+1)
v1 := make([]int, len(t)+1)

for i := 0; i < len(v0); i++ {
v0[i] = i
}

for i := 0; i < len(s); i++ {
v1[0] = i + 1
for j := 0; j < len(t); j++ {
cost := 0
if s[i] != t[j] {
cost = 1
}
v1[j+1] = int(math.Min(float64(v1[j]+1), math.Min(float64(v0[j+1]+1), float64(v0[j]+cost))))
}

for j := 0; j < len(v0); j++ {
v0[j] = v1[j]
}
}
return v1[len(t)]
}

最佳答案

在 Go 1.18 之前,一次性功能是标准方式;例如,the stdlib's sort.go是否在文件顶部附近:

func min(a, b int) int {
if a < b {
return a
}
return b
}

您可能仍希望或需要使用这种方法,以便您的代码在低于 1.18 的 Go 版本上运行!

从 Go 1.18 开始,你可以写一个 generic min function它在运行时与手动编码的单一类型版本一样有效,但适用于任何具有 < 的类型和 >运营商:

func min[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}

func main() {
fmt.Println(min(1, 2))
fmt.Println(min(1.5, 2.5))
fmt.Println(min("Hello", "世界"))
}

discussion更新标准库以添加现有函数的通用版本,但如果发生这种情况,则要等到更高版本。

math.Min(2, 3)碰巧工作是因为numeric constants in Go are untyped .但是,请注意不要将 float64s 一般视为通用数字类型,因为 integers above 2^53 will get rounded if converted to float64 .

关于go - 在 Go 中找到两个整数之间的最小值的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27516387/

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