1

我是 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 中声明一个全局变量,但是我在弄清楚如何使用该变量进行递归时遇到了问题。

4

1 回答 1

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
于 2012-10-19T05:02:34.280 回答