从方案中的列表中获取最长子列表的大小

发布于 2024-12-07 15:58:44 字数 506 浏览 0 评论 0原文

我想从列表中获取最长子列表的大小。

例如

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落在眉间の轻吻 2024-12-14 15:58:44

因此,您的代码的问题在于,即使您继续发现该列表的子列表实际上是最长的,您仍对已计算的列表部分计算 1 长度。例如,对于这种情况,您的代码也返回 5:(getlongest '(a (b (c (d (e))))))

你的方法有点难以轻易解决。我认为,当你递归时,你需要传递更多的数据;如果每次调用 getlongest 都知道当前长度,那么您应该能够获得正确的最大值。

如果这不是家庭作业,那么我将本能地编写相同的函数(不是尽可能高效,但简单:)

(define (get-longest x)
  (cond ((null? x) 0)
        ((atom? x) 1)
        ; else take either the length of this list, or of the longest sub-list
        (else (apply max (length x) (map get-longest x)))))

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:)

(define (get-longest x)
  (cond ((null? x) 0)
        ((atom? x) 1)
        ; else take either the length of this list, or of the longest sub-list
        (else (apply max (length x) (map get-longest x)))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文