2014-04-03 21 views
0

我試圖編寫解決設施位置問題的代碼。我在變量data中創建了一個數據結構。 data是一個包含4個列表的列表。 data[0]是長度爲128的城市名稱列表。其他三個與現在無關。還有一個叫nearbyCities(cityname, radius, data)的函數,它取得城市名稱,半徑和數據,並輸出半徑內的城市列表。假設所有提到的代碼都是正確的,爲什麼會出現這樣的錯誤:'布爾對象沒有歸屬索引'錯誤

File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 232, in locateFacilities 
    File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 162, in served 
    File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 131, in nearbyCities 
AttributeError: 'bool' object has no attribute 'index' 

彈出來了嗎?

下面是三個有問題的功能。 r是我嘗試服務的城市的半徑。前兩個只是第三個幫手,我試圖打電話給他們。錯誤發生在我認爲的while循環中。

def served(city, r, data, FalseList): #Helper Function 1 
    nearbycity=nearbyCities(city, r, data) 
    for everycity in nearbycity: 
     dex1=data[0].index(everycity) 
     FalseList[dex1]=True 
    return FalseList 

def CountHowManyCitiesAreInRThatAreNotServed(city, FalseList, r, data): #Helper Function 2 
    NBC= nearbyCities(city, r, data) 
    notserved=0 
    for element in NBC: 
     if FalseList[data[0].index(element)] == False: 
      notserved= notserved+1 
    return notserved 

def locateFacilities(data, r): 
    FalseList=[False]*128 
    Cities=data[0] 
    Radius=[] 
    output=[] 
    for everycity in Cities: 
     Radius.append(len(nearbyCities(everycity, r, data))) 
    maxito= max(Radius) #Take Radius and find the city that has the most cities in r radius from it. 
    dex= Radius.index(maxito)  
    firstserver=Cities[dex] 
    output.append(firstserver) 
    FalseList=served(firstserver, r, data, FalseList) 

    while FalseList.count(False) > 0: 
     WorkingCityList=[] 
     Radius2=[] 
     temp=[] 
     for everycity in Cities: 
      if FalseList[Cities.index(everycity)] == False: 
       Radius2.append(CountHowManyCitiesAreInRThatAreNotServed(everycity, FalseList, r, data)) 
       temp.append(everycity) 

     maxito=max(Radius2) 
     dex = Radius2.index(maxito) 
     serverC= temp[dex] 
     output.append(serverC) 
     FalseList=served(serverC, r, FalseList, data) 

    output.sort() 
    return output 

這是代碼的其餘部分是如何開始

import re #Import Regular Expressions 

def createDataStructure(): 

    f=open('miles.dat') #Opens file 


    CITY_REG = re.compile(r"([^[]+)\[(\d+),(\d+)\](\d+)") #RegularExpression with a pattern that groups 3 diffrent elements. r" takes a raw string and each thing in parentheses are groups. The first group takes a string until there is actual brackets. The second starts at brackets with two integers sperated by a comma. The third takes an intger. The ending " ends the raw string. 
    CITY_TYPES = (str, int, int, int) # A conversion factor to change the raw string to the desired types. 

    #Initialized lists 
    Cities=[] 
    Coordinates=[] 
    Populations=[] 
    TempD=[] 
    FileDistances=[] 

    #Loop that reads the file line by line 
    line=f.readline() 
    while line: 


     match = CITY_REG.match(line) #Takes the compiled pattern and matches it. Returns false of not matched. 
     if match: 

      temp= [type(dat) for dat,type in zip(match.groups(), CITY_TYPES)] #Returns the matched string and converts it into the desired format. 

      # Moves the matched lists into individual lists 
      Cities.append(temp[0]) 
      Coordinates.append([temp[1],temp[2]]) 
      Populations.append(temp[3]) 
      if TempD: #Once the distance line(s) are over and a city line is matched this appends the distances to a distance list. 

       FileDistances.append(TempD) 
      TempD=[] 


     elif not(line.startswith('*')): # Runs if the line isn't commented out with a "*" or a matched line (line that starts with a city). 

      g=line.split() #This chunck takes a str of numbers and converts it into a list of integers. 

      i=0 
      intline=[] 
      while i != len(g): 
       intline.append(int(g[i])) 
       i+=1   
      TempD.extend(intline) 


     line=f.readline() 
    f.close() #End parsing file 
    FileDistances.append(TempD) #Appends the last distance line 
    FileDistances.insert(0,[]) #For first list 


    i=0 
    j=1 

    while i!= 128: #Loop takes lists of distances and makes them len(128) with corresponding distances 

     FileDistances[i].reverse() #Reverses the current distance list to correspond with distance from city listed before. 
     FileDistances[i].append(0) #Appends 0 because at this point the city distance is it's self. 

     counter=i+1 
     while len(FileDistances[i]) != 128: #Loop that appends the other distnaces. 

      FileDistances[i].append(FileDistances[counter][-j]) 
      counter=counter+1 

     j+=1 
     i+=1 


    cities=[] 

    for i in Cities: #Removes the commas. I dont know why we need to get rid of the commas... 
     new=i.replace(',','') 
     cities.append(new) 


    #Final product <3   
    MasterList=[cities, Coordinates, Populations, FileDistances] 

    return MasterList 

getCoordinates

def getCoordinates(cityname, data): #Basic search function 

    INDEX=data[0].index(cityname) 

    return data[1][INDEX] 

getPopulation

def getPopulation (cityname, data): #Basic search function 

    INDEX=data[0].index(cityname) 

    return data[2][INDEX] 

getDistance的

def getDistance (cityname1, cityname2, data): #Basic search function 

    INDEX=data[0].index(cityname1) 
    INDEX2=data[0].index(cityname2) 

    return data[3][INDEX][INDEX2] 

nearbyCities

def nearbyCities(cityname, radius, data): 

    Cities=data[0] 


    INDEX=Cities.index(cityname) 

    workinglist=data[3][INDEX] #Data[3] is the distance list 
    IndexList=[] 
    index = 0 
    while index < len(workinglist): #Goes through the lists and outputs the indexes of cities in radius r 
     if workinglist[index] <= radius: 
      IndexList.append(index) 
     index += 1 

    output=[] 
    for i in IndexList: #Searches the indexes and appends them to an output list 
     output.append(Cities[i]) 
    output.sort() 
    return output 

文件miles.dat可以在http://mirror.unl.edu/ctan/support/graphbase/miles.dat

+2

nearbyCities是怎樣的?另外,在每個函數的開頭添加帶行號的註釋,以便更容易地發現錯誤。 –

回答

1

很好地發現,似乎data[0]包含一個布爾值,而不是字符串。我在一個空的解釋器中試了這個,並且能夠提出同樣的例外。

Interpreter errors

看來,有一個在您data列表的格式錯誤。爲了找出真正的問題,我們需要看到這一點。

+0

我上傳了其餘的代碼。謝謝您的幫助!數據[0]輸出城市列表 – Shahaed

+0

這樣做很好,但是引發了異常,''bool'對象沒有屬性'index'字面意思是你正在調用一個'.index()'方法布爾('True' /'False')。執行'data.'時出現錯誤。' –

+0

不幸的是,我看不到錯誤可能來自哪裏。我的數據是完全正確的,我不相信我會在程序中隨時破壞它。 – Shahaed

相關問題