0

Im trying to write a code that solves a facility location problem. I have created a data structure in the variable data. data is a list with 4 lists in it. data[0] is a list of city names with a length of 128. The other three are irrelevant for now. There is also a function called nearbyCities(cityname, radius, data) which takes a city name, a radius, and the data and outputs a list of cities within the radius. Assuming that all the code mentioned is correct, why is the error:

  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'

popping up?

Here's the three functions in question. r is the radius of the cities I am trying to serve. The first two are just helpers for the third which I am trying to call. The error is in the while loop I think.

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

This is how the rest of the code starts

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

The file miles.dat can be found at http://mirror.unl.edu/ctan/support/graphbase/miles.dat

1
  • 2
    How does nearbyCities look like? Also, add comments with line numbers at the beginning of each functions, so it will be easier to spot bug. Commented Apr 3, 2014 at 20:04

1 Answer 1

2

Well, it appears that data[0] contains a boolean, and not a string. I tried this in an empty interpreter, and was able to raise the same exception.

Interpreter errors

It appears that there is an error in your data list's format. We would need to see that in order to figure out the true issue.

Sign up to request clarification or add additional context in comments.

3 Comments

I uploaded the rest of the code. Thanks for the help! The data[0] outputs the city list
It's good that you did that, but the exception raised, 'bool' object has no attribute 'index' literally means that you are calling a .index() method on a Boolean (True/False). There is something wrong with you implementation of data.
Unfortunately I can't see where that error could be coming from. My data is sound, and I do not believe I mutilate it anytime during the program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.