Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python recursive function counting the user

The count_users function recursively counts the amount of users that belong to a group in the company system, by going through each of the members of a group and if one of them is a group, recursively calling the function and counting the members. But it has a bug! Can you spot the problem and fix it?

def count_users(group):
    count = 0
    for member in get_members(group):
        count += 1
        if is_group(member):
            count += count_users(member)
    return count
print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18
like image 895
Anne94 Avatar asked Oct 24 '25 11:10

Anne94


2 Answers

def count_users(group):
    count = 0
    for member in get_members(group):
    #count += 1
        if is_group(member):
            count += count_users(member)
        else:
            count+=1
    return count

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18
like image 166
AKSHITA GUPTA Avatar answered Oct 27 '25 00:10

AKSHITA GUPTA


The problem lies in your for loop. Currently you increase your count by 1 for each "member" of the group, even if that member is a group itself. Instead move this line into a new else branch after the if is_group(member), so it will only be increased by either the number of members if member is a group, or 1 if member is not a group.

like image 27
user3631406 Avatar answered Oct 27 '25 02:10

user3631406