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