I'm trying to create a python script for the Huntington-Hill apportionment method. For this, I need the population of each state, the number of seats currently assigned to each state, and value a , where a = p/sqrt(s*(s+1)). I need to identify which state has the largest a value, add one seat to that state and repeat until the state with the smallest population as the largest a . I've created row[3] in my list to store a values but I'm unable to have python identify the largest one.
I've tried to sort row[3] or simply find the max value, but am told 'float' object is not iterable. If I convert it to a string and then sort, it sorts each digit, giving me a list of 9s and then 8s etc.
import math
file_csv = open("statepop2.csv")
data_csv = csv.reader(file_csv)
list_csv = list(data_csv)
for row in list_csv:
row.append(0)
row[3] = int(row[1])/math.sqrt(int(row[2])*(int(row[2])+1))
print(sorted(row[3]))
I'm very new to all this, so any help is much appreciated
Edit: It seems this is a problem with the CSV, not with the sort. I'm not sure what's wrong, nor how to upload my CSV file.
The problem is that row[3]
is an integer, not a list. You cannot sort an integer.
I am not sure what you exactly want to do, but try this:
for row in list_csv:
row.append(0)
row[3] = int(row[1])/math.sqrt(int(row[2])*(int(row[2])+1))
print(max([row[3] for row in list_csv]))
You are trying to sort the value of a itself, hence giving a float as argument to the sorted() function. It is the same of typing:
sorted(4.3)
As 4.3 is not a list but a float, it is not iterable .
I suggest to simply create a list and appending the value to that list, then printing the sorted list.
import math, csv
file_csv = open("statepop2.csv")
data_csv = csv.reader(file_csv)
list_csv = list(data_csv)
rows = []
for row in list_csv:
row.append(0)
row[3] = int(row[1])/math.sqrt(int(row[2])*(int(row[2])+1))
rows.append(row[3])
print(sorted(rows))
If you need some other data from your CSV (ie the country name?) to be displayed along with the a value, just makes rows a dict :
rows = {}
Then you can add a dict entry, having the other piece of info as key :
countryName = row[x]
rows[countryName] = row[3]
Simply use max()
.
a = [1.2, 3.8, 4.9]
b = max(a)
print(b)
# 4.9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.