2013-10-13 91 views
0

我正在研究一個程序,該程序需要一個名稱列表並返回名稱的前二十個出現,而不管性別。Str對象沒有屬性出現

我有點難以理解我做錯了什麼,因爲我正在嘗試使用insert_sort並且它不工作。

這是代碼。

 class babyName(): 
      __slots__ = ("name" , "gender" , "occurences") 

      def __init__(self, name, gender, occurences): 
       self.name = name 
       self.gender = gender 
       self.occurences = occurences 

      def __str__(self): 
       return self.name + "," + self.gender + "," + self.occurences 

     def mkEntry(name, gender, occurences): 
      entry = babyName(name, gender, occurences) 

      return entry 

     def readFile(year): 
      lst = [] 
      lst2 = [] 
      topm = 20 
      topf = 20 
      yob = ("yob" + str(year) + ".txt") 
      for line in open("names/" + yob):  
       line = line.split(",") 
       if line[1] == "F": 
        if topf > 0: 
         entry = mkEntry(line[0], line[1], line[2]) 
         lst.append(entry) 
         topf -= 1 
       elif line[1] == "M": 
        if topm > 0: 
         entry = mkEntry(line[0], line[1], line[2]) 
         lst2.append(entry) 
         topm -= 1 
      mergedlist = lst + lst2 

      return mergedlist 

     def insertion_sort(lst): 
      for i in range(1, len(lst)): 
       h = i - 1 
       val = lst[i].occurences 
       val2 = lst[i-1].occurences 
       while (h >= 0) and (val2 > val): 
        lst[h+1] = lst[h] 
        h = h - 1 
       lst[h+1] = val 

     def main(): 
      year = input("Enter the year of birth:") 
      file = readFile(year) 
      insertion_sort(file) 
      for x in file: 
       print(x) 

     main() 

任何幫助?我不完全知道什麼是錯的......

回答

0
lst[h+1] = val # val isn't a babyName instance 

大概應該是

lst[h+1] = lst[i] 
+0

很好,讓它實際上運行,但現在它不斷返回一個具有相同值的列表反覆.... – Tuskaugur

0

嗯。不應該有移動/插入的東西的佔位符?

def insertion_sort(lst): 
    for i in range(1, len(lst)): 
     # placeholder for the item being moved 
     tmp = lst[i] 
     h = i - 1 
     val = lst[i].occurences 
     val2 = lst[i-1].occurences 
     while (h >= 0) and (val2 > val): 
      lst[h+1] = lst[h] 
      h = h - 1 
     lst[h+1] = tmp 

您可能想看看Wikipedia文章中的僞代碼。

相關問題