Max Alekseyev on Wed, 06 Sep 2023 17:21:06 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: Python combinations() in GP?


One can use forsubsets() here:

? forsubset([5,3],s, print(s) )
Vecsmall([1, 2, 3])
Vecsmall([1, 2, 4])
Vecsmall([1, 2, 5])
Vecsmall([1, 3, 4])
Vecsmall([1, 3, 5])
Vecsmall([1, 4, 5])
Vecsmall([2, 3, 4])
Vecsmall([2, 3, 5])
Vecsmall([2, 4, 5])
Vecsmall([3, 4, 5])

Regards,
Max


On Wed, Sep 6, 2023 at 7:14 AM <hermann@stamm-wilbrandt.de> wrote:
I am porting Python code to GP.

I need Python combinations from itertools:

>>> from itertools import combinations
>>> for i in combinations(range(5),3):
...     print(i)
...
(0, 1, 2)
(0, 1, 3)
(0, 1, 4)
(0, 2, 3)
(0, 2, 4)
(0, 3, 4)
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
>>>

Since GP is 1-based and not 0-based at Python, I came up with this:

$ cat part.gp
sorted(v)=
{
   if(#v<2,return(1));
   if(v[1]>=v[2],return(0));
   sorted(v[2..#v]);
}

{
   forvec(v=vector(3,i,[1,5]),
     if(sorted(v),
       print(v)));
}
$

Which does the right output, but has to skip many not sorted
combinations.
Is there a more efficient GP code for Python combinations?

$ gp -q < part.gp
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
$


Regards,

Hermann.