【问题标题】:Racket - Find lists that has the same element in a 2D listRacket - 在二维列表中查找具有相同元素的列表
【发布时间】:2019-11-17 11:00:23
【问题描述】:

有人可以告诉我如何解决这个问题/给我一个模板吗?我不允许使用 map 或 lambda 或任何其他高级内置函数,只能列出

【问题讨论】:

    标签: racket


    【解决方案1】:

    首先提取与输入字符串关联的国家:

    (define (get-country l s)
      (cond [(empty? (rest l)) (second (second (first l)))]
            [else (if (equal? s (first (first l)))
                      (second (second (first l)))
                      (get-country (rest l) s))]))
    

    然后提取与该国家/地区相关联的所有字符串:

    (define (get-countries l s)
      (cond [(empty? l) '()]
            [else (if (equal? s (second (second (first l))))
                      (cons (first (first l)) (get-countries (rest l) s))
                      (get-countries (rest l) s))]))
    

    然后把它们放在一起:

    (define (same-country l s)
      (get-countries l (get-country l s)))
    

    当我们评估时,我们得到的结果与(list "YUL" "YVR" "YWG" "YYZ") 不同:

    > (same-country alist "YUL")
    (list "YYZ" "YWG" "YUL" "YVR")
    

    所以我们检查结果是否是所需列表的排列。首先我们制作is-permutation:

    (define (is-permutation l1 l2)
      (and (not (and (cons? l1) (empty? l2)))
           (not (and (empty? l1) (cons? l2)))
           (or (and (empty? l1) (empty? l2))
               (and (is-member (first l1) l2)
                    (is-permutation (rest l1)
                                    (remove-one (first l1) l2))))))
    
    (define (is-member e l)
      (and (not (empty? l))
           (or (equal? (first l) e)
               (is-member e (rest l)))))
    
    (define (remove-one e nel)
      (cond [(empty? (rest nel)) '()]
            [else (if (equal? (first nel) e)
                      (rest nel)
                      (cons (first nel) (remove-one e (rest nel))))]))
    

    然后我们可以测试:

    > (is-permutation (same-country alist "YUL")
                      (list "YUL" "YVR" "YWG" "YYZ"))
    #true
    

    【讨论】:

    • 感谢您的回答!虽然我想问如何构建我自己的排序函数来生成一个新列表,其中所有字符串都按升序排列?
    • 与顶级问题无关,但您要查找的内容类似于htdp.org/2019-02-24/…,除了在insert 中使用>= 以降序排列数字,您使用@987654332 @ 以升序排列字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多