在python中使用全局变量

时间:2012-10-19 04:59:07

标签: python c

我是python的新手。我试图将我的一个C程序转换为相应的python程序,但是我无法在python中使用全局变量。我在c和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 :(得分: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