英文:
Translate numpy digitize function into go
问题
Digitize函数返回输入数组中每个值所属的箱子的索引。
以下是Python代码示例 -
x = np.array([0.8, 6.9, 3.5, 1.9])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
inds = np.digitize(x, bins)
print(inds)
array([1, 4, 3, 2])
英文:
Digitize function return the indices of the bins to which each value in input array belongs.
Below code is from python -
x = np.array([0.8, 6.9, 3.5, 1.9])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
inds = np.digitize(x, bins)
print(inds)
array([1, 4, 3, 2])
答案1
得分: 2
这是代码:
package main
import (
"fmt"
"sort"
)
func digitize(x, bins []float64) []int {
inds := make([]int, len(x))
for k, v := range x {
inds[k] = sort.SearchFloat64s(bins, v)
}
return inds
}
func main() {
x := []float64{0.8, 6.9, 3.5, 1.9}
bins := []float64{0, 1, 2.5, 4, 10}
inds := digitize(x, bins)
fmt.Println(inds) // [1 4 3 2]
}
https://golang.org/pkg/sort#SearchFloat64s
英文:
This does it:
package main
import (
"fmt"
"sort"
)
func digitize(x, bins []float64) []int {
inds := make([]int, len(x))
for k, v := range x {
inds[k] = sort.SearchFloat64s(bins, v)
}
return inds
}
func main() {
x := []float64{0.8, 6.9, 3.5, 1.9}
bins := []float64{0, 1, 2.5, 4, 10}
inds := digitize(x, bins)
fmt.Println(inds) // [1 4 3 2]
}
答案2
得分: 0
package main
import (
"errors"
"fmt"
"sort"
)
type arr []float64
func (a arr) Less(i, j int) bool {
return a[i] < a[j]
}
func (in arr) digitize(bins arr) ([]int, error) {
if !sort.SliceIsSorted(bins, bins.Less) {
return nil, errors.New("bins数组未排序")
}
indices := make([]int, len(in))
for i, x := range in {
indices[i] = sort.SearchFloat64s(bins, x)
}
return indices, nil
}
func main() {
var (
x = arr{0.8, 6.9, 3.5, 1.9}
bins = arr{0.0, 1.0, 2.5, 4.0, 10.0}
)
indices, err := x.digitize(bins)
if err != nil {
panic(err)
}
fmt.Println(indices)
}
参考:https://golang.org/pkg/sort#SearchFloat64s
SearchFloat64s 在已排序的 float64 切片中搜索 x,并根据 Search 的规定返回索引。返回值是要插入 x 的索引(如果 x 不存在,则为 len(a))。切片必须按升序排序。
英文:
package main
import (
"errors"
"fmt"
"sort"
)
type arr []float64
func (a arr) Less(i, j int) bool {
return a[i] < a[j]
}
func (in arr) digitize(bins arr) ([]int, error) {
if !sort.SliceIsSorted(bins, bins.Less) {
return nil, errors.New("bins array is not sorted")
}
indices := make([]int, len(in))
for i, x := range in {
indices[i] = sort.SearchFloat64s(bins, x)
}
return indices, nil
}
func main() {
var (
x = arr{0.8, 6.9, 3.5, 1.9}
bins = arr{0.0, 1.0, 2.5, 4.0, 10.0}
)
indices, err := x.digitize(bins)
if err != nil {
panic(err)
}
fmt.Println(indices)
}
Ref: https://golang.org/pkg/sort#SearchFloat64s
> SearchFloat64s searches for x in a sorted slice of float64s and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论