3
$\begingroup$

I have a list of lists of integers that are each sorted numerically. Here is a sample of it: {{2, 8, 9}, {3, 7, 9}, {4, 6, 9}, ...}. I wish to only pick out members which meet the following criteria:

  1. No two elements within it are consecutive:ContainsNone[Union@Differences[#], {1}] &
  2. The length of the list is itself a member of the list:ContainsAny[#, {Length@#}] &]

Each test independently works fine:

In=Select[mylist, ContainsNone[Union@Differences[#], {1}] &]
Out={{3, 7, 9}, {4, 6, 9}, {1, 3, 6, 9}, {1, 4, 6, 8}}

In=Select[mylist, ContainsAny[#, {Length@#}] &]
Out={{3, 7, 9}, {1, 4, 5, 9}, {1, 4, 6, 8}, {2, 4, 5, 8}, {2, 4, 6, 7}, {3, 4, 5, 7}, {1, 2, 3, 5, 8}, {1, 2, 4, 5, 7}, {1, 3, 4, 5, 6}}

However when I attempt to use an And[] function with Select[] to only pick out lists that meet both criteria I am presented with an empty result when clearly at least {3,7,9} meets both criteria:

In=Select[mylist,And[ContainsNone[Union@Differences[#], {1}] &,ContainsAny[#, {Length@#}] &]]
Out={}

Is it that And[] is not working as I intend it inside this Select[] function? Surely if Select[] passes each member one by one, the And[] will return True when it gets to {3,7,9}, no? Or is it some other reason? I know I can just output each and do an Intersection[] but I just want to figure out how to use Select to do what I intend.

$\endgroup$
1
  • 1
    $\begingroup$ Use myList // Select[And[pred1, pred2, ...] /* Through]. $\endgroup$ Commented Sep 16, 2023 at 17:24

1 Answer 1

1
$\begingroup$
list = {{2, 8, 9}, {3, 7, 9}, {4, 6, 9}};

Select[list, 
 ContainsNone[Union @ Differences[#], {1}] && 
   ContainsAny[#, {Length @ #}] &]

{{3, 7, 9}}

Or, if you want the And:

Select[list, 
 And[ContainsNone[Union@Differences[#], {1}], 
   ContainsAny[#, {Length@#}]] &]

{{3, 7, 9}}

$\endgroup$
4
  • $\begingroup$ So I understand correctly, it was me treating each test as a separate function that was causing the issue? I see here you're merging them both into one function? $\endgroup$ Commented Sep 16, 2023 at 16:23
  • 1
    $\begingroup$ Yes, one could say so $\endgroup$
    – eldo
    Commented Sep 16, 2023 at 16:24
  • $\begingroup$ Do you know what it is about Select's innerworkings that would reject an And[] evaluation of two different functions onto one list member? $\endgroup$ Commented Sep 16, 2023 at 16:25
  • 1
    $\begingroup$ The predicate you give to Select must evaluate to either True or False. Your only mistake was, that you duplicated the & and put the ] in the wrong positions (at the end) $\endgroup$
    – eldo
    Commented Sep 16, 2023 at 16:33

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.