我正在尝试在列表中找到最重复的元素。问题是我必须使用count
函数,该函数查找特定值在列表中重复的次数(例如,(count 7 '(4 8 9 2 4 8 9))
=> 0,(count 2 '(4 8 9 2 2 4 8 9 2))
=> 3)。
我完成了count
函数,我认为我接近mode
函数。任何帮助将不胜感激。
(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))]))
答案 0 :(得分:2)
看起来是mode
晚 - 检查之前使用不同方法的question:它假定输入列表已排序。但是当然 - mode
过程可以用count
实现,带有非排序的输入列表,虽然效率较低 - 但它是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
这个想法很简单,计算列表中每个元素的次数,并跟踪看起来最多的元素。
而且仅供参考,这个和其他链接解决方案(需要先执行排序)都不能实现最有效的算法来查找未排序列表中的模式。看到这个answer,那里实现的most-common
过程也会计算列表的模式,但是在O(n)
中。