In: Computer Science
Write a python or java code which can calculate the Shapely-Shubik and Banzhaf indices to determine which state in America has the most power in the primary election.
%matplotlib inline
import powerindex as px
game=px.Game(quota=51,weights=[51,49])
game.calc_banzhaf()
print(game.banzhaf)
#output [1.0, 0.0]
game.calc_shapley_shubik()
print(game.shapley_shubik)
#output [1.0, 0.0]
game=px.Game(51,weights=[50,50])
game.calc()
print(game.banzhaf)
print(game.shapley_shubik)
#output [0.5, 0.5]
[0.5, 0.5]
game=px.Game(4,[3, 2, 1])
game.calc() # again it calculates all available indices
print("Banzhaf index:")
print(game.banzhaf)
print("Shapley-Shubik index:")
print(game.shapley_shubik)
#Output Banzhaf index:
# [0.6, 0.2, 0.2]
# Shapley-Shubik index:
# [0.6666666666666667, 0.16666666666666669, 0.16666666666666669]
countries={"California":4,"Florida":4,"Georgia":4," Louisiana":2,"Michigan":2,"New Jersey":1}
parties=[px.Party(countries[country],country) for country in countries]
game=px.Game(12,parties=parties)
game.calc()
print("Banzhaf index:")
print(game.banzhaf)
print("Shapley-Shubik index:")
print(game.shapley_shubik)
# run this code and you will get this output
#Banzhaf index:
# [0.238, 0.238, 0.238, 0.143, 0.143, 0.00]
# Shapley-Shubik index:
# [0.233, 0.233, 0.233, 0.150, 0.150, 0.00]