为随机分组创建评级系统

Creating a rating system for randomised groups

所以我有这段代码将 (1,2,3,4)(x4) 分为 4 组,我试图找到一种方法来对这些组进行评分。例如。 (1,1,1,1) 是一个很好的组,因为没有其他数字 (1,2,3,4) 是最差的组。那么有没有人知道一种方法来检查组中不同值的数量,例如(1111) 有 1 个值,而 (1,2,3,3) 有 3 个变化。

import numpy
import random
members, n_groups = 4, 4
participants=list(range(1,members+1))*n_groups
#print participants 
random.shuffle(participants)

with open('myfile1.txt','w') as tf:
    for i in range(n_groups):
        group = participants[i*members:(i+1)*members]
        for participant in group:
            tf.write(str(participant)+' ')
        tf.write('\n')

with open('myfile1.txt','r') as tf:
    g = [list(map(int, line.split())) for line in tf.readlines()]
    print(g)
    print(numpy.mean(g, axis=1))

使用上面的代码创建一个简单的函数:

格式为(31432123121)的输入数据可以使用:

def get_rating(group):
    group = str(group)  # needed to use set 
    return len(set(group))

set 将唯一元素的数量排序到集合中

>>> set("1111222233")
set(['1', '3', '2'])
>>> 

然后len就得到了长度。

对于像 (1,2,3,1,2) 这样的输入数据:

def get_rating(group):
    """
    (tuple of ints)->int
    """
    group_str = ""  # create an empty string to rep the nums
    for each_num in group:  # iterate through each of the numbers in the group
        group_str += str(each_num)  # convert each number to a string and append to group_str
    return len(set(group_str))  # return a count of the number of different elements in the input group

print get_rating((4,2,3,4,4,4,1,5))  # simple test for function

与多个列表一起使用:

# global var
my_groups = [[3, 1, 3, 1], [2, 2, 4, 2], [3, 4, 3, 2], [4, 4, 1, 1]]

def get_rating(group):
    """
    (tuple of ints)->int
    """
    group_str = ""
    for each_num in group:
        group_str += str(each_num)
    return len(set(group_str))

# iterates through each list inside the main list.  
# Note that lists and tuples can be treated the same except when you want 
# to change the internal values
for each_grp in my_groups:  
    print get_rating(each_grp),

如果要分行打印,请删除代码最后一行的逗号。