我有两个列表,lst1
和lst2
。我想定义一个函数来检查它们是否共享一些元素。例如:
(share-some-elements? '(a b) '(a c))
⇒真的(share-some-elements? '(a b) '(d e f))
⇒false(share-some-elements? '(a b) '(a b d e))
⇒真的我有一个实现:
(define (share-some-elements? lst1 lst2)
(ormap (λ (x) (member x lst1)) lst2))
检查lst2
中的每个元素是否为lst1
的成员,如果其中任何一个元素为{
},则返回true。
我的问题是:
(all-share-some-elements? '(a b) '(a c) '(a d))
⇒真的(all-share-some-elements? '(a b) '(a c) '(b d))
⇒false(all-share-some-elements? '(a b) '(a c) '(b d a))
⇒真的关于如何在python中的两个列表上执行此操作存在类似的问题: Checking if two lists share at least one element,它并没有完全回答我的问题。
答案 0 :(得分:2)
这两个问题都可以使用一个带有可变数量参数的过程来解决。假设至少传递了一个列表,我们有:
(define (all-share-some-elements? . lists)
(not (null? (apply set-intersect lists))))
说明:
set-intersect
。使用您的示例:
(all-share-some-elements? '(a b) '(a c))
=> #t
(all-share-some-elements? '(a b) '(d e f))
=> #f
(all-share-some-elements? '(a b) '(a b d e))
=> #t
(all-share-some-elements? '(a b) '(a c) '(a d))
=> #t
(all-share-some-elements? '(a b) '(a c) '(b d))
=> #f
(all-share-some-elements? '(a b) '(a c) '(b d a))
=> #t