将表表示为矩阵

2024-09-28 23:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个包含3个字段的数据库表:stringtitle、inta、intb。 A和B的范围是1到500。
我想用矩阵5x5表示部分值。 所以(1,1)将是A和B都最低的字符串; (5,5)A和B都最高; (1,5)将具有最低A和最高B。依此类推。
我应该使用哪种算法?


Tags: 字符串算法数据库矩阵intaintbstringtitle
2条回答

你有吗

title  A  B
one    1  1
two    1  2
three  2  1
four   3  3
five   4  4
six    5  5
seven  5  1
eight  1  5

等等。。。?在

简化为3x3矩阵,看起来像

^{pr2}$

问题是,(2,2)指向什么?平均值?好的,在5x5矩阵中呢? 你的定义缺少一些信息。在

上述矩阵的算法为:

  1. 对于A和B,计算最小值、最大值、平均值
  2. 向数据库查询元组(Amin,Bmin),(Aavg,Bmin),(Amax,Bmin)等
  3. 将值填充到矩阵中

附加:如果没有匹配项,请尝试最小值、最大值和平均值的范围

我已经在这里设置了一个模拟程序,注释将描述这些步骤。在

首先,我生成一些数据:一系列元组,每个元组包含一个字符串和两个代表a和B分数的随机数

接下来,我将A和B的范围分成五个等距的箱子,每个箱子代表一个单元格的最小值和最大值。在

然后我连续查询数据集以提取每个单元格中的字符串。在

根据您使用的实际数据结构和存储,有上百种优化方法。在

from random import random

# Generate data and keep record of scores
data = []
a_list = []
b_list = []
for i in range(50):
    a = int(random()*500)+1
    b = int(random()*500)+1
    rec = { 's' : 's%s' % i,
            'a' : a,
            'b' : b
             }
    a_list.append(a)
    b_list.append(b)
    data.append(rec)

# divide A and B ranges into five bins

def make_bins(f_list):
    f_min = min(f_list)
    f_max = max(f_list)
    f_step_size = (f_max - f_min) / 5.0
    f_steps = [ (f_min + i * f_step_size,
                 f_min + (i+1) * f_step_size)
                for i in range(5) ]
    # adjust top bin to be just larger than maximum
    top = f_steps[4]
    f_steps[4] = ( top[0], f_max+1 )
    return f_steps

a_steps = make_bins(a_list)
b_steps = make_bins(b_list)

# collect the strings that fit into any of the bins
# thus all the strings in cell[4,3] of your matrix
# would fit these conditions:
# string would have a Score A that is
# greater than or equal to the first element in a_steps[3]
# AND less than the second element in a_steps[3]
# AND it would have a Score B that is
# greater than or equal to the first element in b_steps[2]
# AND less than the second element in a_steps[2]
# NOTE: there is a need to adjust the pointers due to
#       the way you have numbered the cells of your matrix

def query_matrix(ptr_a, ptr_b):
    ptr_a -= 1
    from_a = a_steps[ptr_a][0]
    to_a = a_steps[ptr_a][1]

    ptr_b -= 1
    from_b = b_steps[ptr_b][0]
    to_b = b_steps[ptr_b][1]

    results = []
    for rec in data:
        s = rec['s']
        a = rec['a']
        b = rec['b']
        if (a >= from_a and
            a < to_a and
            b >= from_b and
            b < to_b):
            results.append(s)
    return results

# Print out the results for a visual check
total = 0
for i in range(5):
    for j in range(5):
        print '=' * 80
        print 'Cell: ', i+1, j+1, ' contains: ',
        hits = query_matrix(i+1,j+1)
        total += len(hits)
        print hits
print '=' * 80
print 'Total number of strings found: ', total

相关问题 更多 >