未定义Python 2.7全局名称。

时间:2021-12-31 16:48:32

Writing a python program to perform merge sort, and I get a Global Name not found error

编写一个python程序来执行合并排序,我得到一个全局名称,而不是发现错误。

### Program for Merge Sort ###
def merge(numbers, l, m, r):
    n1 = m-l-1 ### Size of the left side array ###
    n2 = r-l  ### Size of the right side array ###
    ### Temporary Lists ###
    for i in range(n1):
        L[i] = numbers[l+i]

    for j in range(n2):
        R[j] =  numbers[m+j+1]

    ### The following code eliminates searching if any of the lists have become empty ###
    L[n1] = float("inf")
    R[n1] = float("inf")

    i = 0
    j = 0

    for k in range(l,r+1):
        if(L[i]<=R[j]):
            numbers[k] = L[i]
            i+=1
        else:
            numbers[k] = R[j]
            j+=1

def mergeSort(numbers, l, r):
    if (l<r):
        m = l+(r-1)/2 ### Avoids overflow for large numbers
        mergeSort(numbers, l, m)
        mergeSort(numbers, m+1, r)
        merge(numbers, l, m, r)

I have my driver program calling the mergeSort function on the user input numbers and when I run the code, I get an error saying Global Name 'R' is not defined

我的驱动程序调用了用户输入号上的mergeSort函数,当我运行代码时,我得到一个错误,说全局名'R'没有定义。

Traceback (most recent call last):
  File "merge_sort.py", line 55, in <module>
    main()
  File "merge_sort.py", line 50, in main
    mergeSort(numbers, 0, size-1)
  File "merge_sort.py", line 32, in mergeSort
    mergeSort(numbers, l, m)
  File "merge_sort.py", line 33, in mergeSort
    mergeSort(numbers, m+1, r)
  File "merge_sort.py", line 34, in mergeSort
    merge(numbers, l, m, r)
  File "merge_sort.py", line 10, in merge
    R[j] =  numbers[m+j+1]
NameError: global name 'R' is not defined`

What am I doing wrong?

我做错了什么?

2 个解决方案

#1


3  

Indeed you never defined name R. Fix that by replacing:

实际上,你从来没有定义过名字r,用替换的方法来解决这个问题:

for j in range(n2):
    R[j] =  numbers[m+j+1]

with:

:

R = [numbers[m+j+1] for j in range(n2)]

(and similarly for L, by the way -- I'm surprised you don't get that as an error since you access the name L before the name R).

(顺便说一下,顺便说一下,我很惊讶,你没有把它作为一个错误,因为你在名字R之前访问了这个名字)。

#2


1  

You need to initialize your temporary lists, L and R, before using them.

在使用临时列表、L和R之前,您需要初始化它们。

L = []
R = []
for i in range(n1):
    L[i] = numbers[l+i]

for j in range(n2):
    R[j] =  numbers[m+j+1]

#1


3  

Indeed you never defined name R. Fix that by replacing:

实际上,你从来没有定义过名字r,用替换的方法来解决这个问题:

for j in range(n2):
    R[j] =  numbers[m+j+1]

with:

:

R = [numbers[m+j+1] for j in range(n2)]

(and similarly for L, by the way -- I'm surprised you don't get that as an error since you access the name L before the name R).

(顺便说一下,顺便说一下,我很惊讶,你没有把它作为一个错误,因为你在名字R之前访问了这个名字)。

#2


1  

You need to initialize your temporary lists, L and R, before using them.

在使用临时列表、L和R之前,您需要初始化它们。

L = []
R = []
for i in range(n1):
    L[i] = numbers[l+i]

for j in range(n2):
    R[j] =  numbers[m+j+1]