python - 在python中使用全局变量

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

最佳答案

每次递归调用都会将计数设置回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/

相关文章:

python - ImageDataGenerator.flow() 给出 IOError : [Errno 2] No such file or directory

python - 适应性函数来分割嵌套列表?

c++ - 如何在 waf 构建系统中安装具有不同名称的库?

python - 使用 python 查找 HTML 标签

c++ - 在共享内存中保持固定大小的符号

c stdin 二维数组文件输入

c - 在 AVR Atmega324A 上多路复用七段显示器

python - Airflow CeleryExecutor - 'int' 对象在 Celery 中没有属性 'startswith'

我可以在不使用 c 中的循环的情况下将 1d 数组复制到 2d 结构中吗?

c - 使用位交织的 3D Morton 编码,传统指令集与 BMI2 指令集