OneMoreError
OneMoreError

Reputation: 7728

Using global variables in python

I am new to python. I am trying to convert one of my c programs to corresponding python program, however I am not able to use global variable in python. My code in both c and python are :


#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

I think I know how to declare a global variable in python, but I am having problem in figuring out how to use that variable with recursion.

Upvotes: 1

Views: 266

Answers (1)

John La Rooy
John La Rooy

Reputation: 304355

Each recursive call will set the count back to 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

Upvotes: 4

Related Questions