gpt4 book ai didi

python - Colab 中的 Cython : "cdef struct Rectangle" (line 9) identified as syntax error

转载 作者:行者123 更新时间:2023-11-30 18:34:29 26 4
gpt4 key购买 nike

我在 Siraj Raval 的最新直播中展示了这段代码:

%laod_ext Cython
%cython
#memory management helper for Cython
from cymem.cymem import Pool
#good old python
from random import random

#The cdef statement is used to declare C variables,types, and functions
cdef struct Rectangle:
#C variables
float w
float h

#the "*" is the pointer operator, it gives value stored at particular
address
#this saves memory and runs faster, since we don't have to duplicate the
data
cdef int check_rectangles_cy(Rectangle* rectangles, int n_rectangles, float
threshold):
cdef int n_out = 0
# C arrays contain no size information => we need to state it explicitly
for rectangle in rectangles[:n_rectangles]:
if rectangle.w * rectangle.h > threshold:
n_out += 1
return n_out

#python uses garbage collection instead of manual memory management
#which means developers can freely create objects
#and Python's memory manager will periodically look for any
# objects that are no longer referenced by their program
#this overhead makes demands on the runtime environment (slower)
# so manually memory management is better
def main_rectangles_fast():
cdef int n_rectangles = 10000000
cdef float threshold = 0.25
#The Poool Object will save memory addresses internally
#then free them when the object is garbage collected

cdef Pool mem = Pool()
cdef Rectangle* rectangles = <Rectangle*>mem.alloc(n_rectangles, sizeof(Rectangle))
for i in range(n_rectangles):
rectangles[i].w = random()
rectangles[i].h = random()
n_out = check_rectangles_cy(rectangles, n_rectangles, threshold)
print(n_out)

运行时,此代码输出以下错误:

File "ipython-input-18-25198e914011", 'line 9'
cdef struct Rectangle:
SyntaxError: invalid syntax

我哪里写错了?视频链接:https://www.youtube.com/watch?v=giF8XoPTMFg

最佳答案

你有一个错字。替换

%laod_ext Cython

%load_ext Cython

事情应该按预期进行。

关于python - Colab 中的 Cython : "cdef struct Rectangle" (line 9) identified as syntax error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137503/

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