Deniz Can Tufekci
Deniz Can Tufekci

Reputation: 167

UnboundLocalError: local variable 'result' referenced before assignment

I've problem which cannot fix. When I run my code I get these errors:

UnboundLocalError: local variable 'result' referenced before assignment

My code is as follows:

def findMaxPages(userInlist):
    size = len(userInlist)
    readList = []
    if size == 0:
        result = (0, readList)
    if size == 1:
        readList.append(userInlist[0])
        result = (readList[0].getSumPage(), readList)
    if size > 1:
        dic0, dic1 = userInlist[0].getPagesDic(), userInlist[1].getPagesDic()
        exist=0
        for keys in dic0.keys():
            if keys in dic1: 
                exist+=1
        if exist == 0:
            nextUser = userInlist[0]
            withPage, withToTake = findMaxPages(userInlist[1:])
            withPage += nextUser.getSumPage()
            withoutPage, withoutToTake = findMaxPages(userInlist[1:])
            if withPage > withoutPage:
                readList.append(nextUser)
                result = (withPage, withToTake + readList)
            else:
                result = (withoutPage, withoutToTake)
    return result

pages, readerlist = findMaxPages(users)

"users" is a list whose elements are a Person object.

class Person(object):
    def __init__(self, name, min, max):
        self.name = name
        self.min = min
        self.max = max

    def getName(self):
        return self.name

    def getMinPage(self):
        return self.min

    def getMaxPage(self):
        return self.max

    def getSumPage(self):
        return self.max - self.min + 1

    def getAllPages(self):
        allPages = []
        for pages in range(self.min, self.max + 1):
            allPages.append(pages)
        return allPages

    def getPagesDic(self):
        return createDic(self.getAllPages())

createDic() method returns the list in the parameter as a dictionary.

The algorithm is trying to do this: There are people who read pages from a particular book (min = the first page read from the book, max = the last page read from the book). Let's create a group of these people so that no one in the group reads a common page and the group reads the maximum number of pages. Thanks a lot for the help.

Upvotes: 0

Views: 1262

Answers (1)

Nicolas Iceberg
Nicolas Iceberg

Reputation: 743

Add result = None in the very top of the findMaxPages function. That's the "easy" solution.

The more detailed part is that there are branches in your if statements where result is not defined at all. To make it accessible for the return statement, you need to make sure your variable was declared in all branches of if/elif/else statements.

Upvotes: 2

Related Questions