pari

How can I know if a number is inside a list in PARI/GP?


I am trying to know if a number is inside a PARI/GP list but I do not know how to do it, this is my code:

mylist = listcreate();

... here I add some numbers with  listput(mylist,XXXX)

/* How can I do the condition in the if... */
if(mynumber in mylist,print("SUCCESS"),print("ERROR"))

I am migrating from Python to PARI/GP some of my scripts and I am lost in those basic things, the manual is a little bit difficult to follow. Thank you!


Solution

  • Edit: In the 10 years since I originally posted this, the Set data structure has changed and is now much more interchangeable with Vecs. So if you have your data in a sorted vector, you can simply use setsearch on it directly. Further, if all you want is to find all elements in a set/sorted vector a that are also in the set/sorted vector b, you can just use setintersect.


    You can test if a given value is in a list, vector, or column vector like so:

    inList(list, value)=for(i=1,#list, if(list[i]==value, return(i))); 0
    

    or less efficiently like

    inlist(list, value)=#select(n->n==value, list) > 0
    

    Your example would then look like

    if(inList(mylist, mynumber), print("SUCCESS"), print("ERROR"))
    

    But if you're going to be doing a lot of queries, it's worthwhile to use a binary search instead:

    myset = Set(mylist);
    if(setsearch(myset, mynumber), print("SUCCESS"), print("ERROR"))