2013-10-20 68 views
0

我正在制定1950年至1990年期間拉美國年中人口的計劃。第一行爲50,第二行爲51,等等。該計劃提取信息,然後顯示年份中人口增長最多的一年,人口增長率最小的一年以及日期範圍內人口年平均變化。年均變化?

我可以做前兩個,但平均年度更改顯示不正確。我被給了一個暗示,顯然我在30歲時錯過了一條線。平均每年的變化只是一直顯示爲零? :(

def main(): 
    #setup variables 
    yearly_change = [] 
    change=0.0 
    total_change=0 
    average_change=0 
    greatest_increase=0 
    smallest_increase=0 
    greatest_year=0 
    smallest_year=0 
    BASE_YEAR=1950 
    try: 
     #open the file for reading 
     input_file = open("USPopulation.txt", "r") 
     #read all the lines in the in file into a list 
     yearly_population= input_file.readlines() 
     #turn all read lines into a number 
     for i in range(len(yearly_population)): 
      yearly_population[i] = float(yearly_population[i]) 
     #calculate the change in population size for each two years 
     for i in range(1,len(yearly_population)): 
      change = yearly_population[i] - yearly_population[i-1] 

      #MISSING SINGLE LINE HERE? 

      #if this is the first year, set trackers to its value 
      if i==1: 
       greatest_increase = change 
       smallest_increase = change 
       greatest_year = 1 
       smallest_year = 1 
      #this is not the first change in population size 
      #update the trackers if relevent 
      else: 
       if change>greatest_increase: 
        greatest_increase = change 
        greatest_year = i 
       elif change<smallest_increase: 
        smallest_increase = change 
        smallest_year = i 
      total_change = float(sum(yearly_change)) 
      average_change = total_change/40 
      print("The average annual change in population during the time period is",\ 
        format(average_change, '.2f')) 
      print("The year with the greatest increase in population was", 
BASE_YEAR+greatest_year) 
      print("The year with the smallest increase in population was", 
BASE_YEAR+smallest_year) 
      input_file.close() 
    except IOError: 
     print("The file could not be found") 
    except IndexError: 
     print("There was an indexing error") 
    except: 
     print("An error occurred") 

main() 

按照要求,這裏是輸入文件中的幾行:

151868 
153982 
156393 
158956 
161884 
165069 
168088 
171187 
174149 
177135 
179979 

這僅僅是一個基本的.txt文件的第一行是該國1950年的人口,第二個是在1951年的人口,等等

回答

1

你這樣做:

total_change = float(sum(yearly_change)) 
average_change = total_change/40 

但你設置yearly_change到一個空的列表,這裏:

yearly_change = [] 

然後永遠不會改變它。所以你試圖計算一個空列表的總數,然後嘗試計算它的平均值,所以它顯然將爲零。你的程序應該以某種方式更新yearly_change,或者你應該計算一些其他列表的總和。

+0

哦,一個大文件,咄。我應該注意到我沒有任何更新。謝謝。 – user2901098

0

你需要在你的代碼中加入這一行更新yearly_change領域:

for i in range(1,len(yearly_population)): 
     change = yearly_population[i] - yearly_population[i-1] 
     yearly_change.append(change) #new line 

這應該存儲在現場的每一個變化,所以當你試圖計算平均值,列出不會是空的了。

+0

謝謝你的幫助! – user2901098

0

如果它是你可以使用

for i in xrange(1, len(yearly_population)): 
    change = yearly_population[i] - yearly_population[i-1] 
    yearly_change.append(change) 
+0

xrange是個好主意,謝謝。 – user2901098