Set origin to Matrix_world bottom center of Lego bricks's bound box

I have a lego 3D objects, in blender 2.92.0. And I would to set the origin to Matrix_world bottom center of Lego bricks's bound box, then set all bricks to z = 0.

I am a newbie in blender, so I'm trying run the code from batFINGER .

import bpy
from mathutils import Matrix, Vector

def origin_to_bottom(ob, matrix=Matrix()):
me = ob.data
mw = ob.matrix_world
local_verts = [matrix @ Vector(v[:]) for v in ob.bound_box]
o = sum(local_verts, Vector()) / 8
o.z = min(v.z for v in local_verts)
o = matrix.inverted() @ o
me.transform(Matrix.Translation(-o))

mw.translation = mw @ o

for o in bpy.context.scene.objects:
if o.type == 'MESH':
origin_to_bottom(o)
#origin_to_bottom(o, matrix=o.matrix_world) # global

and this code:

from mathutils import Matrix, Vector
import numpy as np

def origin_to_bottom(ob, matrix=Matrix(), use_verts=False):
me = ob.data
mw = ob.matrix_world
if use_verts:
data = (v.co for v in me.vertices)
else:
data = (Vector(v) for v in ob.bound_box)

coords = np.array([matrix @ v for v in data])
z = coords.T
mins = np.take(coords, np.where(z == z.min()), axis=0)

o = Vector(np.mean(mins, axis=0))
o = matrix.inverted() @ o
me.transform(Matrix.Translation(-o))

mw.translation = mw @ o It's looking like something is wrong, but I can't find out the reason. So, what can I do now?

guys. I get the answer about the question. Thanks for the help from Martynas Žiemys

this is the code:

def origin_to_bottom(ob):
if ob.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT', toggle=True)

d = ob.data
m = ob.matrix_world

bounds_center = (sum((m @ Vector(b) for b in ob.bound_box), Vector()))/8
difference = m.translation - bounds_center
local_difference = difference @ m
for v in d.vertices:
v.co += local_difference
m.translation -= difference

difference = Vector((0,0,0))
bound = min((m @ v.co).z for v in d.vertices)
difference.z = m.translation.z - bound

local_difference = difference @ m
for v in d.vertices:
v.co += local_difference
m.translation -= difference