4
$\begingroup$

I would like to know how i can determine if two elements in a list exist. For example the setup would look like this:

liste = {"b", "d1", "a","z"}
MemberQ[{{"b", "a"}}, liste]

One problem i have is that it should not depend on the order of the two element, i.e. {"b", "a"} == {"a", "b"} that i want to check. I just want to know if these exist in a given list.

$\endgroup$
2
  • 9
    $\begingroup$ Hello, have a look at the documentation for ContainsAll , cheers! $\endgroup$ Nov 16, 2021 at 19:57
  • $\begingroup$ Intersection can do this: Intersection[liste, {"b", "a"}] != {} $\endgroup$ Nov 17, 2021 at 11:25

3 Answers 3

2
$\begingroup$
list = {"b", "d1", "a", "z"};

ab = {"a", "b"};

ContainsAll[list, ab]

True

SubsetQ[list, ab]

True

Last @ UniqueElements[{list, ab}] == {}

True

$\endgroup$
2
$\begingroup$
list = {"b", "d1", "a", "z"};

ab = {"a", "e"};

An alternative is the following:

Thread[# -> Thread[Lookup[Counts[Catenate[{list, #}]], #] &@# > 1]] &@ab

(*{"a" -> True, "e" -> False}*)
$\endgroup$
1
$\begingroup$

Using OrderlessPatternSequence:

Clear["Global`*"];

f[k_List, elems_List] := 
  If[Cases[k, {OrderlessPatternSequence[Sequence @@ elems, ___]}, 
     All] == {}, False, True];

test = {{"b", "c", "a", "e", "c"}, {"a", "e", "c", "d", "a"}, {"d", 
    "d", "e", "c", "d"}, {"a", "e", "d", "d", "d"}, {"e", "b", "d", 
    "d", "a"}};

Usage:

f[#, {"a", "b"}] & /@ test

{True, False, False, False, True}

f[#, {"b", "c", "e"}] & /@ test

{True, False, False, False, False}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.