将两个列表组合成一个列表球拍 [英] Combine two lists into one list Racket

查看:213
本文介绍了将两个列表组合成一个列表球拍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:

我有两个数字列表,例如(list1 3 6 7)和(list2 1 6 4 7)。现在我必须将两者合并到(list3 1 3 4)。所以6和7都在list1和list2。 List3包含所有只出现一次的数字。我希望你得到我的意思,如果不只是问我:s!
这里我的开始:

I have two list of numbers for example (list1 3 6 7) and (list2 1 6 4 7). Now I have to combine both into (list3 1 3 4). So 6 and 7 are both in list1 and list2. List3 contains all numbers which occur only once. I hope u get what i mean if not just ask me :s! Here my start:

(define (diff list1 list2)
  (cond
    [(empty? list1) list2] ;; If list1 was empty return directly list2
    [(empty? list2) list1] ;; If list2 was empty return directly list1
    [else
      (???



我知道我必须比较第一个list1与list2中的每个数字,然后递归如何编程?

I know that I have to compare first list1 with every number in list2 and then recursiv again. But how do I programm it?

推荐答案

这里有一个不同的,希望不太棘手的实现它需要对两个传入列表进行排序;相比之下,Óscar的实现不需要排序列表,但是它是O(n2)。)

Here's a different, hopefully less-tricky, implementation. (It's O(n), but it requires both of the incoming lists to be sorted; in comparison, Óscar's implementation does not required sorted lists, but it's O(n²).)

(define (diff lhs rhs)
  (let loop ((result '())
             (lhs lhs)
             (rhs rhs))
    (cond ((null? lhs) (append-reverse result rhs))
          ((null? rhs) (append-reverse result lhs))
          (else (let ((a (car lhs))
                      (b (car rhs)))
                  (cond ((< a b) (loop (cons a result) (cdr lhs) rhs))
                        ((< b a) (loop (cons b result) lhs (cdr rhs)))
                        (else (loop result (cdr lhs) (cdr rhs)))))))))



Example:

> (diff '(3 6 7) '(1 4 6 7))
(1 3 4)


$ b b

append-reverse 来自 SRFI 1 ,所以在Racket你必须(需要srfi / 1)

append-reverse is from SRFI 1, so in Racket you have to (require srfi/1).

这篇关于将两个列表组合成一个列表球拍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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