import csv

def fitness(l,partition):
    totalhappyness = 0
    for p in range(0,max(partition)+1):
        leng = len(l[0])
        total = [0]*(leng)
        totalv = 0
        for j in range(0,len(l)):
            if partition[j] == p:
                row = l[j]
                for i in range(1,leng):
                    total[i] = total[i]+int(row[i])
                    totalv = totalv+int(row[i])

        totalp = [0]*(leng)
        for i in range(1,leng):
            if totalv!=0:
                totalp[i] = 1.*total[i]/totalv

        for j in range(0,len(l)):
            if partition[j] == p:
                row = l[j]
                happyv = 0
                votes = 0
                for i in range(1,leng):
                    happyv = happyv + int(row[i])*totalp[i]
                    votes = votes+int(row[i])
                totalhappyness = totalhappyness + happyv
                #print row[0],1.*happyv/votes
    return totalhappyness
        #print totalp

csvin = csv.reader(open('spain2011.csv'), delimiter=',', quotechar='"')
head = csvin.next()
l = []
for row in csvin:
    l.append(row)

partition = [0]*len(l)

state = [0]*len(l)

newpart = 1
for newpart in range(1,5):
    maxi = 0
    while maxi != -1:
        maxfitness = fitness(l,state)
        maxi = -1
        for i in range(0,len(l)):
            if state[i]!=newpart:
                ant = state[i]
                state[i] = newpart
                f = fitness(l,state)
                if f > maxfitness:
                    maxfitness = f
                    maxi = i
                state[i] = ant
        if maxi != -1:
            state[maxi] = newpart
            #print l[maxi][0]
    print fitness(l,state)