Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting a "Referenced before assignment" error?

This Python program will determine whether the input array is a mountain array or not. I’ve found answers on stackoverflow for this same error in other programs I’ve made, but not this one. It seems to work without issue when a valid mountain array is the input, but I’m having issues when I change the first half of the test array to make it an invalid. Rather than it returning False, which is the goal, I’m getting this error: "UnboundLocalError: local variable ‘y’ referenced before assignment". Also, I was getting the same error for the z variable, so I added the "else" statements and it fixed it. Can’t figure out why it didn’t fix the y variable as well. Here’s my code:

def validMountainArray(arr):
        maxElem = max(arr)
        maxIndex = arr.index(maxElem)
        if len(arr) < 3:
            return False
        else:
            beginning = arr[:maxIndex]
            end = arr[maxIndex + 1:]

            for i in range(1, len(beginning) - 1):
                if beginning[i + 1] > beginning[i]:
                    y = True
                else:
                    y = False
            for i in range(1, len(end) - 1):
                if end[i + 1] < end[i]:
                    z = True
                else:
                    z = False

            if y == True and z == True:
                return True
            else:
                return False

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Those for-loops aren’t guaranteed to be executed. It’s possible that the range could end up with 0 numbers in it, and thus no loop will occur and y and/or z will never be assigned. To fix this, define those variables as False at the start of the function.

def validMountainArray(arr):
    y = False
    z = False
    maxElem = max(arr)
    maxIndex = arr.index(maxElem)
    # etc
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading