0

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!

iadvd
  • 179
  • 1
  • 2
  • 12
  • 1
    Please, see the question http://stackoverflow.com/questions/27753897/finding-entry-of-vector-in-pari-gp/29568708#29568708. Note, you need not the "index mode" there. – Piotr Semenov May 26 '15 at 05:07
  • @PiotrSemenov thank you! indeed I have read the question and your answer before, but it talks about vectors, not lists, so I thought it was not possible to use it with lists. – iadvd May 26 '15 at 05:13
  • 1
    Small remark is here just in case :) Function `select` from PARI/GP 2.7.3 (recent release) works well with lists. Please, see how to check if a random list contains a number `10`: `lst = List(vector(1000,i,random(100))); select((e) -> e == 10, lst) != []` – Piotr Semenov May 26 '15 at 07:55

1 Answers1

2

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"))
Charles
  • 11,269
  • 13
  • 67
  • 105
  • 1
    @iadvd: No problem -- I'll do what I can for all the [tag:pari] and [tag:pari-gp] questions. :) – Charles Jun 23 '15 at 19:26