December 24, 2010

Python Huntington Hill method

The following python code implements the Huntington Hill method which was used to generate the apportionment details in my previous post.

import math

def huntington_hill(popln,num_seats):
  num_states = len(popln)
  representatives = [1]*num_seats
  std_divs = [math.sqrt(2)]*num_states
  for j in range(num_states,num_seats):
    max = 0
    for i in range(1,num_states):
      if (popln[i][1]/std_divs[i]) > (popln[max][1]/std_divs[max]):
        max = i        
    representatives[max] +=  1    
    std_divs[max]=math.sqrt(representatives[max] * (representatives[max]+1))
  return representatives
  
  
POPULATION= [("JAMMU & KASHMIR",10143700),("HIMACHAL PRADESH",6077900),("PUNJAB",24358999),
("CHANDIGARH",900635),("UTTARANCHAL",8489349),("HARYANA",21144564),("DELHI",13850507),
("RAJASTHAN",56507188),("UTTAR PRADESH",166197921),("BIHAR",82998509),
("SIKKIM",540851),("ARUNACHAL PRADESH",1097968),("NAGALAND",1990036),
("MANIPUR",2166788),("MIZORAM",888573),("TRIPURA",3199203),
("MEGHALAYA",2318822),("ASSAM",26655528),("WEST BENGAL",80176197),
("JHARKHAND",26945829),("ORISSA",36804660),("CHHATTISGARH",20833803),
("MADHYA PRADESH",60348023),("GUJARAT",50671017),("DAMAN & DIU",158204),
("DADRA & NAGAR HAVELI",220490),("MAHARASHTRA",96878627),("ANDHRA PRADESH",76210007),
("KARNATAKA",52850562),("GOA",1347668),("LAKSHADWEEP",60650),
("KERALA",31841374),("TAMIL NADU",62405679),("PONDICHERRY",974345),
("ANDAMAN & NICOBAR ISLANDS",356152)
]

NUMBER_SEATS= 545

mps = huntington_hill(POPULATION,NUMBER_SEATS)
for i in range(len(POPULATION)):
  print POPULATION[i][0]+","+str(POPULATION[i][1])+","+str(mps[i])

1 comment:

nivedhitha said...

very nice and great blog with useful information Student internship on python course