5
我想構建一個python類型的int矩陣,一個64位有符號整數。cython/numpy類型的數組
cdef matrix33():
return np.zeros((3,3),dtype=int)
cdef do_stuf(np.ndarray[int, ndim=2] matrix):
...
return some_value
def start():
print do_stuf(matrix33())
它編譯正確的,但是當我運行它,我不斷收到此錯誤:
ValueError: Buffer dtype mismatch, expected 'int' but got 'long'
我不能跟蟒蛇長的工作,但我不知道如何正確地轉換爲64 INT。
UPDATE
奧基。我很確定我正確使用了Cython。我寫的代碼是在capture go/atari去的遊戲中進行minmax搜索。
迄今爲止最調用的函數是這些:
cdef isThere_greedy_move(np.ndarray[np.int64_t, ndim=2]board, int player):
cdef int i, j
for i in xrange(len(board)):
for j in xrange(len(board)):
if board[i,j] == 0:
board[i,j] = player
if player in score(board):
board[i,j] = 0
return True
board[i,j] = 0
return False
# main function of the scoring system.
# returns list of players that eat a stone
cdef score(np.ndarray[np.int64_t, ndim=2] board):
scores = []
cdef int i,j
cdef np.ndarray[np.int64_t, ndim = 2] checked
checked = np.zeros((board.shape[0], board.shape[1]), dtype = int)
for i in xrange(len(board)):
for j in xrange(len(board)):
if checked[i,j] == 0 and board[i,j] !=0:
life, newly_checked = check_life(i,j,board,[])
if not life:
if -board[i,j] not in scores:
scores.append(-board[i,j])
if len(scores) == 2:
return scores
checked = update_checked(checked, newly_checked)
return scores
# helper functions of score/1
cdef check_life(int i, int j, np.ndarray[np.int64_t, ndim=2] board, checked):
checked.append((i,j))
if liberty(i,j,board):
return True, checked
for pos in [[1,0],[0,1],[-1,0],[0,-1]]:
pos = np.array([i,j]) + np.array(pos)
if check_index(pos[0],pos[1],len(board)) and board[pos[0],pos[1]] == board[i,j] and (pos[0],pos[1]) not in checked:
life, newly_checked = check_life(pos[0],pos[1],board,checked)
if life:
checked = checked + newly_checked
return life, checked
return False, [] # [] is a dummy.
cdef liberty(int i,int j, np.ndarray[np.int64_t, ndim=2] board):
for pos in [np.array([1,0]),np.array([0,1]),np.array([-1,0]),np.array([0,-1])]:
pos = np.array([i,j]) - pos
if check_index(pos[0],pos[1],len(board)) and board[pos[0],pos[1]] == 0:
return True
return False
我真的認爲這將是照耀用Cython的機會。 爲了解決3x3的捕獲去:
的Python 2.7確實一致2.28秒,與用Cython它是一致的2.03 兩者都與蟒時間模塊和小於60℃°
一個i7處理器立即測試對我來說,問題是,如果我要切換到哈斯克爾或C++爲這個項目......
謝謝你,現在的代碼運行正確。但是,它的運行速度與我宣佈一切都很長時一樣快。我知道長時間的物體並不快,因爲它不會溢出並且被對待不同(使用更多的週期)。我想使用一個可以溢出並且比python類型更快的int。 – Ihmahr 2012-02-28 12:04:07
此外,解釋蟒蛇的速度超過10%,這讓我很懷疑我沒有正確的類型... – Ihmahr 2012-02-28 12:10:41
@ user1020753:類型是正確的。加速取決於你在你的功能中做什麼。 – 2012-02-28 13:02:18