我是 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 中声明一个全局变量,但我在弄清楚如何通过递归使用该变量时遇到问题。
最佳答案
每次递归调用都会将计数设置回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
关于python - 在python中使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12967645/