eda
eda

Reputation: 55

UnboundLocalError: local variable 'row' referenced before assignment

I have written a function, which calculates the Levenshtein distance between two given strings. Two files containing a certain number of strings are read, the function is called and the distance between them is calculated. The program is run and all distances are calculated and printed. However, once it reaches the end, an error appears.

This is the piece of code I have written:

def MyLevenshtein(String1, String2):
    rows = len(String1) + 1
    columns = len(String2) + 1
    distance = [[0 for x in range(columns)] for x in range(rows)]
    for i in range(1, rows):
        distance[i][0] = i
    for i in range(1, columns):
        distance[0][i] = i
    for column in range(1, columns):
        for row in range(1, rows):
            if String1[row - 1] == String2[column - 1]:
                cost = 0
            else:
                cost = 2
            distance[row][column] = min(distance[row - 1][column] + 1,  # deletion
                                 distance[row][column - 1] + 1,  # insertion
                                 distance[row - 1][column - 1] + cost) #substitution

    Distance = distance[row][column]
    return  Distance
source = open('D:/TestWords.txt', 'r', encoding="utf-8")
target = open('D:/RefWords.txt', 'r', encoding="utf-8")
source = source.read().splitlines()
target = target.read().splitlines()
for i in source:
    for j in target:
        print(i, j, MyLevenshtein(i, j))

This is the error that appears:

UnboundLocalError: local variable 'row' referenced before assignment

Upvotes: 0

Views: 1856

Answers (2)

Barak Itkin
Barak Itkin

Reputation: 4877

The row variable is initialized by the inner for loop, but is then accessed outside. Quoting the official documentation:

The for-loop makes assignments to the variables(s) in the target list. [...] Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop.

While the row variable can be used in a block outside the for loop, it can only be used so if the loop had some iterations (see also here)

Upvotes: 1

Jorge D
Jorge D

Reputation: 43

Generally speaking, you are defining/creating row in a statement which may or may not run (depending on the loop condition) but you are attempting to read its value in any case

Upvotes: 0

Related Questions