构建最大堆和迭代

luc*_*sKo 2 python iteration

我有两个问题:

1)最近我尝试构建一个最大堆.即使我读过CLRS,我也无法找到它.以下是我的代码......

def maxHeapify(list, index):
    int = index
    left = (int+1) * 2 - 1
    right = (int+1) * 2
    largest = 0
    if left < len(list):
        if (left <= len(list)) & (list[left] >= list[int]):
            largest = left
        else: 
            largest = int
    if right < len(list):
        if (right <= len(list)) & (list[right] >= list[largest]):
            largest = right
    else:
        pass
    if largest != int:
        listNew = swapWithinList(list, int, largest)
        listNew = maxHeapify(listNew, largest)
    else:
        return listNew


def swapWithinList(list, id1, id2):
    num1 = list[id1]
    num2 = list[id2]
    listNew = list[:id1]
    listNew.append(num2)
    listNew = listNew + list[(id1+1):id2]
    listNew.append(num1)
    listNew = listNew + list[(id2+1):]
    return listNew
Run Code Online (Sandbox Code Playgroud)

我提供输入,但控制台只是说:

UnboundLocalError: local variable 'listNew' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

这是否意味着我将退货声明放在错误的一行或者我没有提到的东西?

2)什么是迭代?

当我问这个问题时,我有点尴尬.但什么是迭代?Wiki说这个过程的每次重复都意味着它,所以它是循环给出每一轮的结果吗?

迭代器似乎是Python中的基本元素,迭代器和迭代之间有什么区别?

geo*_*org 6

1:

没有进一步的评论,这里的代码改编自维基百科:

def max_heapify(A, i):
    left = 2 * i + 1
    right = 2 * i + 2
    largest = i
    if left < len(A) and A[left] > A[largest]:
        largest = left
    if right < len(A) and A[right] > A[largest]:
        largest = right
    if largest != i:
        A[i], A[largest] = A[largest], A[i]
        max_heapify(A, largest)

def build_max_heap(A):
    for i in range(len(A) // 2, -1, -1):
        max_heapify(A, i)
Run Code Online (Sandbox Code Playgroud)

例:

def ptree(A, i=0, indent=0):
    if i < len(A):
        print '  ' * indent, A[i]
        ptree(A, i * 2 + 1, indent + 1)
        ptree(A, i * 2 + 2, indent + 1)

A = range(9) 
build_max_heap(A)
ptree(A)
Run Code Online (Sandbox Code Playgroud)

结果:

 8
   7
     3
       1
       0
     4
   6
     5
     2
Run Code Online (Sandbox Code Playgroud)

如果你有任何疑问,请告诉我们.

2:

python中的迭代在技术上是一个重复调用某个对象的next()方法直到它引发StopIteration异常的过程.拥有此next方法的对象称为Iterator.能够为调用代码提供迭代器的对象称为Iterable.