2012-10-19 86 views
1

我是python的新手。我試圖將我的C程序之一轉換爲相應的Python程序,但是我無法在Python中使用全局變量。我在C和Python代碼是:在python中使用全局變量


#include <stdio.h> 
int globalcount; 

void noofways(int firstnumchosen,int sum,int numofnum) 
{ 
if(sum<0) 
    return; 

if(sum==0 && numofnum!=0) 
    return; 

if(sum==0 && numofnum==0){ 
    globalcount++; 
    return; 
} 

if(numofnum<=0) 
    return; 

if(firstnumchosen>sum) 
    return; 

noofways(firstnumchosen+1,sum,numofnum); 
noofways(firstnumchosen+1,sum-firstnumchosen,numofnum-1); 
} 

int main() 
{ 
noofways(1,8,3); 
printf("Required number: %d",globalcount); 
return 0; 
} 

def noofways(firstnumchosen, sum, numofnum): 
    global count 
    count=0 
    if sum<0: 
     return 
    if sum==0 and not(numofnum==0): 
     return 
    if sum==0 and numofnum==0: 
     count+=1 
     return 
    if numofnum<=0: 
     return 
    if firstnumchosen>sum: 
     return 
    noofways(firstnumchosen+1,sum,numofnum) 
    noofways(firstnumchosen+1,sum-firstnumchosen,numofnum-1) 

res=noofways(1,8,3); 
print count 

我想我知道如何聲明Python中的全局變量,但我在搞清楚如何有問題通過遞歸使用該變量。

+1

以何種方式是不工作的代碼?它看起來像它正在打印0,這是我所期望的。此外,你爲什麼使用遞歸全局變量?爲什麼不只是返回你感興趣的變量? –

+1

將'count = 0'移到函數之外 – jfs

+3

我會注意到Python和C在抽象方面是如此不同,試圖將代碼從一種語言重新實現到另一種語言是一個壞主意。最好的問題是問自己原來想做什麼,然後從頭開始寫 - 這樣你最終會得到一種以Pythonic方式工作的Python,這將更容易閱讀和維護。 –

回答

4

每次遞歸調用設置計數回0

def noofways(firstnumchosen, sum, numofnum): 
    global count 
    # don't set count to 0 here 
    if sum<0: 
     return 
    if sum==0 and not(numofnum==0): 
     return 
    if sum==0 and numofnum==0: 
     count+=1 
     return 
    if numofnum<=0: 
     return 
    if firstnumchosen>sum: 
     return 
    noofways(firstnumchosen+1,sum,numofnum) 
    noofways(firstnumchosen+1,sum-firstnumchosen,numofnum-1) 

# set count to 0 here 
count = 0 
res=noofways(1,8,3); 
print count 
+0

是的,這個工程..謝謝! – OneMoreError