Move CENTER (not pivot) to SELECTED array of (edges, vertex, faces)
Bmesh version

The origin is local coordinate (0, 0, 0)

In local (vertex) space the selected location vector o is the average of selected vert coordinates   Make that the origin point by subtracting vector o from all verts' coordinates.

Then move the object to counter the shift in local coords.  The vector t  is the equivalent global space translation, of local space translation o.

Test script. Edit mode. Select verts, run script.

import bpy
import bmesh
from mathutils import Vector, Matrix
context = bpy.context
ob = context.object
me = ob.data

bm = bmesh.from_edit_mesh(me)
selected_verts = [v.co for v in bm.verts if v.select]
# average of selected verts
o = sum(selected_verts, Vector()) / len(selected_verts)
# make this the new origin
for v in bm.verts:
    v.co -= o
# move the object

mw = ob.matrix_world
t = mw * o - mw * Vector()
mw.translation += t

bmesh.update_edit_mesh(me)
me.update()