import json from math import sqrt from statistics import mean first = [(1, 6), (2, 5), (3, 4)] second = [(7, 12), (8, 11), (9, 10)] def pearson(points): x, y = zip(*points) # 用离差内积除以两列离差的长度,不需要显式除 n-1。 mean_x, mean_y = mean(x), mean(y) dx = [value - mean_x for value in x] dy = [value - mean_y for value in y] cross = sum(a * b for a, b in zip(dx, dy)) return cross / sqrt(sum(a * a for a in dx) * sum(b * b for b in dy)) pooled = pearson(first + second) within = [pearson(points) for points in (first, second)] assert abs(pooled - 25 / 29) < 1e-12 and within == [-1, -1] result = {"pooled_r": pooled, "within_r": within} print("LAB_RESULT " + json.dumps(result, ensure_ascii=False))