返回列表中值的方式? (方案) [英] Way of returning median value of a list? (scheme)

查看:60
本文介绍了返回列表中值的方式? (方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个名为median的过程,该过程采用列表的中值.如果列表是偶数,那么我将返回两个中间数字.我脑子里全盘想出了逻辑,但是我不确定如何完成.注意:我试图避免使用list-ref,因为它将使问题变得微不足道. 到目前为止,我的代码如下所示.

I'm attempting to make a procedure named median that takes the median value of a list. If the list is even, then I will return the two middle numbers. I have the logic all thought out in my head, but I'm not sure how to complete it. NOTE: I am trying to avoid using list-ref, as it would trivialize the problem. So far, my code looks like the following.

(define (median lst)
(if (null? lst)
   '()
    (if (even? lst) ; ends here

现在,我要解决的问题是这个.

Now, my approach to the problem is this.

Odd #- Return the value of the "car#" that's in place of (/ (+ (length lst) 1) 2)
3; 2nd car      (1 100 3)    => 100
5; 3rd car      (1 2 100 4 5)  => 100
7; 4th car      (1 2 3 100 5 6 7)  => 100
Even # - Return the value of the "car#" that's in place of (/ (length lst) 2) AND (+ (/ (length lst) 2) 1)
2; 1st and 2nd car         (1 2) => 1 2
4; 2nd and 3rd car         (1 20 30 4) => 20 30

但是,我似乎无法提出一种可以递归实现此伪代码的方法.

However, I cant seem to come up with a way that could recursively implement this pseudocode.

不确定是否有人愿意提供帮助,但是我最终编写了一个迭代过程,该过程将获取任何奇数列表的中值索引值.我现在的麻烦是实现将使代码适用于偶数列表的某些东西,以及无法返回列表中的值的东西:

Not sure if anyone is still out there willing to help, but I ended up writing an iterative procedure that will take the median index value for any odd list. My trouble now is implementing something that will make the code work for an even list, and also something that doesn't return the value in a list:

(define (median-index-odd lst)
    (define (median-index-iter1 lst times_carred)
        (if (null? lst)
           '()
            (if (= times_carred (/ (+ (length lst) 1) 2)) 
                (list (car lst))            
                (median-index-iter1 (cdr lst) (+ 1 times_carred)))))
                (median-index-iter1 lst 0))

我还提出了一个单独的过程来在列表为偶数时查找中位数索引:

I've also came up with a seperate procedure for finding the median index when the list is even:

(define (median-index-even lst)
    (define (median-index-iter2 lst times_carred)
        (if (null? lst)
           '()
            (if (= times_carred (/ (length lst) 2)) 
                (list (car lst) (cadr lst))            
                (median-index-iter2 (cdr lst) (+ 1 times_carred)))))
                (median-index-iter2 lst 0))

推荐答案

(define (median L)
 (if (null? L)
     (error "No median of empty list")
     (let loop ((L1 L) (L2 L))
       (cond ((null? (cdr L2)) (car L1))
             ((null? (cddr L2)) (list (car L1) (cadr L1)))
             (else (loop (cdr L1) (cddr L2))))))

分为两个列表,一次获取第一个列表,一次获取第二个列表

split into two lists take the first one at a time, the second two at a time

这篇关于返回列表中值的方式? (方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆