gpt4 book ai didi

sorting - 是否有包含 `argsort` 实现或包装器的 Nim 库?

转载 作者:行者123 更新时间:2023-12-05 04:13:46 29 4
gpt4 key购买 nike

我正在寻找 argsort 的版本,例如 as exists in numpyin fortran . Nim 中是否有 argsort 的实现……或者 Nim 在某些库中是否可以访问?它不见了,似乎有点令人惊讶。

更新

以下似乎适用于 argsort:

proc argsort[T](a : T) : seq[int] =
result = toSeq(0..a.len - 1)
sort(result, proc (i, j: int): int = cmp(a[i], a[j]))

不过,据推测,它可以更有效地本地编写并避免函数指针....

最佳答案

它还没有变得灵活,但是 Arraymancer 有一个 argsort here

import arraymancer,algorithm,sequtils

proc argsort*[T](t: Tensor[T], order = SortOrder.Ascending): Tensor[int] =
## Returns the indices which would sort `t`. Useful to apply the same sorting to
## multiple tensors based on the order of the tensor `t`.
##
## Sorts the raw underlying data!
# TODO: should we clone `t` so that if `t` is a view we don't access the whole
# data?
assert t.rank == 1, "Only 1D tensors can be sorted at the moment!"
proc cmpIdxTup(x, y: (T, int)): int = system.cmp(x[0], y[0])
# make a tuple of input & indices
var tups = zip(toOpenArray(t.storage.Fdata, 0, t.size - 1),
toSeq(0 ..< t.size))
# sort by custom sort proc
tups.sort(cmp = cmpIdxTup, order = order)
result = newTensorUninit[int](t.size)
for i in 0 ..< t.size:
result[i] = tups[i][1]

let x = @[3,9,4,1,5].toTensor()

echo x.argsort()

产生:

Tensor[system.int] of shape [5]" on backend "Cpu"
3 0 2 4 1

try it out here

关于sorting - 是否有包含 `argsort` 实现或包装器的 Nim 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831528/

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