blender sequences and randon access?

(panzi) #1

Hi.

I wondered if all the sequences you can find in blenders python API (like mesh.edges) are random access? Is e.g. mesh.edges[n] O(n) or O(1)?

0 Likes

(panzi) #2

Obviously in the edge case it is O(1).

blender/source/blender/python/api2_2x/Mesh.c

static MEdge * MEdge_get_pointer( BPy_MEdge * self )
{
    if( self->index >= self->mesh->totedge )
        return (MEdge *)EXPP_ReturnPyObjError( PyExc_RuntimeError,
                "MEdge is no longer valid" );
    return &self->mesh->medge[self->index];
}
0 Likes

(panzi) #3

But for group.objects[n] it is O(n).

blender/source/blender/python/api2_2x/Group.c

static PyObject *GroupObSeq_item( BPy_GroupObSeq * self, int i )
{
    Group *group= self->bpygroup->group;
    int index=0;
    PyObject *bpy_obj;
    GroupObject *gob;
    
    GROUP_DEL_CHECK_PY(self->bpygroup);
    
    for (gob= group->gobject.first; gob && i!=index; gob= gob->next, index++) {}
    
    if (!(gob))
        return EXPP_ReturnPyObjError( PyExc_IndexError,
                          "array index out of range" );
    
    bpy_obj = Object_CreatePyObject( gob->ob );

    if( !bpy_obj )
        return EXPP_ReturnPyObjError( PyExc_RuntimeError,
                "PyObject_New() failed" );

    return (PyObject *)bpy_obj;
    
}
0 Likes

(ideasman42) #4

a really quick way to get an entire list randomized do this…


import random
edges = list(me.edges)
random.shuffle(edges) # randomizes in place

works for any sequence type

or for a sinle item…


import random
edge = me.edges[int(random.random() * len(me.edges))]

there is no standard way for the python api to do random access

0 Likes

(panzi) #5

No, I do not want to randomize access, I want random access! :wink:
“…the ability to access an arbitrary element of a sequence in equal time…”

I want to know which sequences in blender have O(1) costs and which have O(n) costs for accessing the n-th element.

0 Likes