gpt4 book ai didi

list - 查找具有给定总和的子列表

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

给定一个列表 L=(M,A1,A2,...,An) .查找子列表(如果存在)L1=(Ai,Ai+1,...,Ai+k), i+k<=N, i>=1,为此 M=Ai+Ai+1+...Ai+k

例如 1:L=(12 1 3 -16 5 7 8 2 2), M=12结果:L=((1 3 -16)(5 7)(8 2 2))对于 1+3-16=12, 5+7=12, 8+2+2=12

例子L=(14 1 15 -1 14 5 6)结果:L=((15 -1)(14))对于 1=14->no , 1+15=14->no , 1+15-1=14->no , 1+15-1+14=14->no , 1+15-1+14+5=14->no , 1+15-1+14+5+6=14->no
我们继续下一项 15=14->no , 15-1=14->YES!提取物 (15 -1)我们继续下一项 14=14->YES!提取物 (14)我们继续下一项 5=14->no , 5+6=14->no完成结果 (15 -1) (14)

如何在 Lisp 中解析它?

我的代码

(setq l '(6 1 2 3 6 14 3))
(setq comb nil)
(setq rez nil)
(defun sublist (lst)
(secondfunction (car lst) (cdr lst))
)
(defun pairnil (list1)
(mapcar #'(lambda (x) (cons x nil)) list1)
)
(defun pair (a list1)
(mapcar #'(lambda (x) (append x (list a))) list1)
)
(defun secondfunction (head other)
(run (cdr other) (cdr other) (pairnil other) (cdr(pairnil other)) (pairnil(car(pairnil other))))
(final comb head nil)
)
(defun final (lst el result)
(if (>(length lst) 0)
(progn
(if(eq(loop for x in (car lst) sum x) el) (final (cdr lst) el (append result (cons (car lst) nil)))
(if(>(length lst) 0)(final (cdr lst) el result )))
)
(setq rez result)
))
(final comb (car l) nil)
(defun run (lst1 ilst1 lst2 ilst2 temp)
(if (eq(car ilst1) nil) (setq comb lst2))
(when (>(length lst1)0)
(if (>(length ilst1)0) (run lst1 (cdr ilst1) (append lst2 (pair (car ilst1) temp)) ilst2 (append temp (pair (car ilst1) temp))))
(if (=(length ilst1)0) (run (cdr lst1) (cdr lst1) lst2 (cdr ilst2) (pairnil(car ilst2))))
))
(sublist l)

结果 ((6) (1 2 3) (1 2 3) (3 3)) ,但这不能正常工作。在示例中,我已经解释了它应该如何工作。

最佳答案

一个简单的方法:

map over all sublists of list and append the results
map over all sublists of this reversed sublist and append the results
when the sum of the items is M then collect a list of the reverse sublist

需要的功能:

  • mapcon 用于映射
  • reverse 用于反转
  • reduce 求和

关于list - 查找具有给定总和的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46885389/

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