Scheme “方案模式”;列表“;功能
我试图找到列表中重复次数最多的元素。问题是我必须使用Scheme “方案模式”;列表“;功能,scheme,racket,Scheme,Racket,我试图找到列表中重复次数最多的元素。问题是我必须使用count函数,该函数查找特定值在列表中重复的次数(例如,(count 7'(4 8 9 2 4 8 9))=>0,(count 2'(4 8 9 2 2))=>3)。 我完成了计数功能,我想我已经接近模式功能。任何帮助都将不胜感激 (define (count item list) (cond [(null? list) '()] [(= item (car list)) (+ 1 (count item (cdr lis
count
函数,该函数查找特定值在列表中重复的次数(例如,(count 7'(4 8 9 2 4 8 9))
=>0,(count 2'(4 8 9 2 2))
=>3)。
我完成了计数
功能,我想我已经接近模式
功能。任何帮助都将不胜感激
(define (count item list)
(cond
[(null? list) '()]
[(= item (car list)) (+ 1 (count item (cdr list)))]
[#t (count item (cdr list))]))
(define (mode lst)
(cond
[(null? lst) '()]
[(> (count (car lst) lst) (mode (cdr lst))) (car lst)]
[else (mode (cdr lst))]))
现在是晚上,就像它看起来一样-检查一个使用不同方法的前一个:它假设输入列表已排序。但是当然,模式
过程可以通过非排序输入列表的计数
来实现,虽然效率较低,但它是一种O(n^2)
解决方案:
(define (mode lnum)
(let loop ((lst lnum) ; list to traverse
(max-counter 0) ; number of times the mode appears
(max-current #f)) ; the mode
(if (null? lst) ; if the list is empty
max-current ; return the mode
(let ((n (count (car lst) lnum))) ; # of times current element appears
(if (> n max-counter) ; if it appears more times
(loop (cdr lst) n (car lst)) ; then we found a new maximum
(loop (cdr lst) max-counter max-current)))))) ; else continue
想法很简单,计算列表中每个元素的次数,并跟踪出现次数最多的元素
仅供参考,无论是本解决方案还是其他链接解决方案(要求先执行排序),都没有实现在未排序列表中查找模式的最有效算法。看到这一点,在那里执行的
最常见的过程也会计算列表的模式,但在O(n)
中,count
函数不正确。你们测试了吗?我看到了,但不幸的是我不得不使用计数函数来解决这个问题