2012-11-18 28 views
2

我的操作系統不支持Sage 5.4,因此我現在只能使用5.0。 定義這個函數在Python中沒有註冊語法錯誤,我不認爲它在Sage 5.4中犯了錯誤(如果可能,我會很感激的。)我想知道它爲什麼在5.0中失敗。sage 5.0令人困惑的語法錯誤

def num_matchings(G): 
    if min(G.degree_sequence())== 0 or G.num_edges()==0: 
     return 0 
    elif G.num_edges()==1: 
     if G.edges()[0][2] ==None: 
      return 1 
     else: 
      return G.edges()[0][2] 
    else: 
     H = copy(G) 
     K = copy(G) 
     e = G.edges()[0] 
     if e[2] ==None: 
      w=1 
     else: 
      w = e[2] 
     H.delete_edge(e) 
     K.delete_vertices([e[0],e[1]]) 
     return num_matchings(H) + w*num_matchings(K) 

的第一個錯誤,我得到當我嘗試定義是

File "<ipython console>", line 4 ==Integer(1): ^ SyntaxError: invalid syntax
,他們堆在後。在我看來,語法看起來很好。
我在Mac OS 10.5上使用GCC 4.0.1。

任何幫助非常感謝。

回答

2

旁白:錯字在.delete_vertives()]

你的語法本身是好的。但是,從錯誤消息看來,您只是簡單地將代碼複製並粘貼到控制檯中。這隻適用於某些非常簡單的情況。你也使用縮進標籤,這也可能導致整個其他一系列頭痛。你應該切換到4-space選項卡。

如果要將代碼插入實時控制檯,則可以使用%paste(如果可以,則從剪貼板複製)或%cpaste

例如,如果我複製和粘貼代碼,我得到:

sage: def num_matchings(G): 
....:   if min(G.degree_sequence())== 0 or G.num_edges()==0: 
....:    return 0 
....:  elif G.num_edges()==1: 
------------------------------------------------------------ 
    File "<ipython console>", line 4 
    ==Integer(1): 
    ^
SyntaxError: invalid syntax 

sage:   if G.edges()[0][2] ==None: 
....:     return 1 
------------------------------------------------------------ 
    File "<ipython console>", line 2 
SyntaxError: 'return' outside function (<ipython console>, line 2) 

,但如果我用%cpaste與4-空間相當於(可惜%paste不工作對我的5.4.1安裝在當下):

sage: %cpaste 
Pasting code; enter '--' alone on the line to stop. 
: 
:def num_matchings(G): 
: if min(G.degree_sequence())== 0 or G.num_edges()==0: 
:  return 0 

[etc.] 

:  K.delete_vertices([e[0],e[1]]) 
:  return num_matchings(H) + w*num_matchings(K) 
:-- 
sage: num_matchings(graphs.LadderGraph(5)) 
8 
+0

完美。非常感謝! – WKA

+1

+1 - 從來不知道'%cpaste'(甚至'%paste' :)) – RocketDonkey