从方案中的列表中获取最长子列表的大小
我想从列表中获取最长子列表的大小。
例如
(getlongest ((a) b (demn) (ad (cmgcyumld ) a) ))
返回 9 因为 (cmgcyumld ) 的大小为 9。
我写了这个函数
(define getlongest
(lambda (ls)
(cond
((null? ls)0)
(else
(cond
((atom? (car ls))
(+ 1 (getlongest (cdr ls))))
(else
(max (getlongest(car ls)) (getlongest(cdr ls)))))))))
但是如果我写
(getlongest ((a) (a (ddde) m)))
我得到 5。有人能帮我解决这个问题吗?
谢谢
I would like to get the size of the longest sublist from a list.
for example
(getlongest ((a) b (d e m n) (a d (c m g c y u m l d ) a) ))
returns 9 since (c m g c y u m l d ) has size 9.
I wrote this function
(define getlongest
(lambda (ls)
(cond
((null? ls)0)
(else
(cond
((atom? (car ls))
(+ 1 (getlongest (cdr ls))))
(else
(max (getlongest(car ls)) (getlongest(cdr ls)))))))))
However if I write
(getlongest ((a) (a (d d d e) m)))
i get 5. Can anyone help me to fix this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,您的代码的问题在于,即使您继续发现该列表的子列表实际上是最长的,您仍对已计算的列表部分计算 1 长度。例如,对于这种情况,您的代码也返回 5:
(getlongest '(a (b (c (d (e))))))
。你的方法有点难以轻易解决。我认为,当你递归时,你需要传递更多的数据;如果每次调用
getlongest
都知道当前长度,那么您应该能够获得正确的最大值。如果这不是家庭作业,那么我将本能地编写相同的函数(不是尽可能高效,但简单:)
So the problem with your code is that you're counting 1 length for the part of a list you've already counted, even if you go on to find that a sub-list of that list is actually the longest. For example, your code returns 5 for this case, too:
(getlongest '(a (b (c (d (e))))))
.Your approach is sort of hard to fix easily. You'll need to pass more data down when you recurse, I think; if each call to
getlongest
knew the current length, then you should be able to get the right maximum.If this isn't homework, here's how I would instinctively write the same function (not as efficient as possible, but simple:)