gpt4 book ai didi

python - 重新分配链表元素的 'next' 链接时 Numba 降低错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:15 26 4
gpt4 key购买 nike

下面的代码是我用numba实现的链表(相关例子可以看hereherehere)。remove 函数删除位于 index 位置的元素。(请注意,这里假设 index 始终是有效位置)要删除这样的元素 (index),我们会执行类似 element[index-1].next -> element[index+1] 的赋值。但是 numba 似乎不喜欢我这样做:

from numba import deferred_type,optional
from numba import int64
from numba import jitclass,njit

list_type = deferred_type()

spec = [
('data',int64),
('next',optional(list_type))
]
@jitclass(spec)
class List(object):
def __init__(self,data,next):
self.data = data
self.next = next

def prepend(self, data):
return List(data, self)

list_type.define(List.class_type.instance_type)

def length(stack):
i = 0
while stack is not None:
stack = stack.next
i+=1
return i

@njit
def remove(stack,index):
prev = None
if index == 0:
stack = stack.next
else:
cur = stack
i = 0
while cur is not None:
if index == i:
break
i = i+1
prev = cur
cur = cur.next
prev.next = cur.next
return stack

def runme():
from numpy.random import randint
a = randint(0,100,10)

list_ = None

for n in a:
if list_ is None:
list_ = List(n,None)
else:
list_ = list_.prepend(n)
print(length(list_))

indexes = list(range(len(a)))
for i in indexes[::-1]:
list_ = remove(list_,i)
print(length(list_))

if __name__ == '__main__':
runme()

它在 prev.next = cur.next 行中断并出现以下错误:

numba.errors.LoweringError: Failed at nopython (nopython mode backend)
No definition for lowering ?instance.jitclass.List#14bebc8<data:int64,next:?DeferredType#140432587762264>.next = ?DeferredType#140432587762264
File "numba_test.py", line 43
[1] During: lowering "(prev).next = $70.2" at numba_test.py (43)

看起来 prev.next 无法重新分配,但我不太确定这里发生了什么。

我正在使用 numba 0.35.0python 3.6.2

有什么想法吗?

谢谢。


现状

该错误是 Numba 中的错误。更多信息,请前往相应问题:https://github.com/numba/numba/issues/2606

最佳答案

看起来 nopython 模式确实支持此功能。只需使用“普通”jit 装饰器。如果需要,这会回退到纯 Python:

from numba import jit

@jit
def remove(stack,index):
prev = None
if index == 0:
stack = stack.next
else:
cur = stack
i = 0
while cur is not None:
if index == i:
break
i = i+1
prev = cur
cur = cur.next
prev.next = cur.next
return stack

因为 njit 等同于 jit(nopython=True)

测试输出:

10
0

关于python - 重新分配链表元素的 'next' 链接时 Numba 降低错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47232035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com