本文介绍了方案模式功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到列表的模式

假设列表按升序排序

这里是我的模式函数

 (define freq 
(lambda(l)
(cond((null ()()()()()()()()()()()() (car l)))))
(else(freq(cdr l)))
)))

(freq'(4 4 4 4 5 7 9 9 9 ))=>应该返回4,但它返回9而不是


解决方案

这是我的解决方案,这与Óscar的解决方案类似,但集中在一个地方的最长/获胜结果的更新:

 (define(longest-运行lst)
(让循环((结果#f)
(cur #f)
(count 0)
(最长0)
(第1st))
(cond((>计数最长)
(循环当前计数计数lst))
((null?lst)result)
((eqv?(car lst) (循环结果curl(+ count 1)最长(cdr lst)))
(else
(循环结果(car lst)1最长(cdr lst))))))

我认为我的解决方案更短,更干净,重复性更低,但Óscar的解决方案具有更新变量次数更少:他的解决方案只在运行结束时更新变量,而最小值每当当前长度超​​过目前为止所见的最长长度时,e更新变量。


I am trying to find the mode of a list

Assuming the list is sorted ascending order

Here is my mode function

 (define freq
   (lambda (l)
     (cond ((null? l)l)
           ((null? (cdr l))l)
           ((not(equal? (car l) (car(cdr l))))(freq(cdr(delete l (car l)))))
           (else (freq (cdr l)))
 )))

   (freq '(4 4 4 4 5 7 9 9 9)) => should returns 4 but its returning 9 instead
解决方案

Here's my solution, which is similar to Óscar's solution but centralises the update of the longest/winning result in one place:

(define (longest-run lst)
  (let loop ((result #f)
             (cur #f)
             (count 0)
             (longest 0)
             (lst lst))
    (cond ((> count longest)
           (loop cur cur count count lst))
          ((null? lst) result)
          ((eqv? (car lst) cur)
           (loop result cur (+ count 1) longest (cdr lst)))
          (else
           (loop result (car lst) 1 longest (cdr lst))))))

I think my solution is shorter, cleaner, and less repetitive, but Óscar's solution has the advantage of updating the variables fewer times: his solution only updates the variables at the end of a run, whereas mine updates the variables whenever the current length is longer than the longest length seen so far.

这篇关于方案模式功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:41