gpt4 book ai didi

按 LISP 中的索引号从最大值到最小值对列表进行排序?

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:18 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,它接受一个列表,将其从高到低排序,然后给出列表中元素的原始位置,从高到低排序。另外,我希望返回的列表中没有重复项。

所以..

(LargestNumberIndex '( 1 23 101 5 6 5 )

应该返回

(2 1 4 3 5 0)

不是

(2 1 4 3 3 0)

目前我的函数看起来像这样:

    (defun LargestNumberIndex (listofnums Indexes) 
;; make a copy of the list to sort
(setf listcopy (copy-list listofnums))
;; sort list from high to low
(setf sortlist (sort listcopy #'>))
;; compare the elements from both lists to determine the
;; position
(loop for i from 0 below Indexes collect
(position (nth i sortlist) listofnums :test #'equal))

))

我不知道要添加什么才能让它工作。有人有什么想法吗?

最佳答案

备注

  • 不要对局部变量使用 SETF 或 SETQ(使用 LET)
  • 对代码进行缩进和格式化
  • 在名字中使用破折号,不要使用 CamelCase
  • LOOP 可以遍历列表:不要像以前那样使用 NTH

修饰、排序、取消修饰

(也称为 Schwartzian transform)

(defun largest-number-index (list)
(mapcar #'second
(stable-sort
(loop
for index from 0
for element in list
collect (list element index))
#'>
:key #'first)))

(largest-number-index '(1 23 101 5 6 5))
=> (2 1 4 3 5 0)

关于按 LISP 中的索引号从最大值到最小值对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447353/

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