Xenon
Xenon

Reputation: 35

Creating a rating system for randomised groups

So I have this code that groups (1,2,3,4)(x4) into 4 groups, I was trying find a way to rate these groups. E.G. (1,1,1,1) is a good group since there are no other numbers (1,2,3,4) would be the worst group. So does anyone know a way to check the number of different values in a group e.g. (1111) have 1 value, where as (1,2,3,3) has 3 changes.

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))

Upvotes: 1

Views: 72

Answers (1)

srattigan
srattigan

Reputation: 664

Using the above to create a simple function:

For input data of the format (31432123121) you can use:

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

set will sort the number of unique elements into sets

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

then len just gets the length.

For input data like (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

To use with many lists:

# 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),

Remove the comma on the last line of code if you want to print them on separate lines.

Upvotes: 1

Related Questions