182k views
5 votes
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?

This is the code :

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

User Kenlyn
by
4.6k points

1 Answer

3 votes

Answer:

# The count variable should be defined in a global scope.

count = 0

def count_users(group):

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

Step-by-step explanation:

The count variable should be defined in a global scope which means that it shouldn't be defined inside the scope of the count_users function.

The reason is that count_users is a recursive function and when it is called recursively then it will be setting the count variable to 0 again and again, hence instead of keeping the count of users, it will lose the value all the time serving no purpose. But when it's defined outside the function then it will not initialized again in the recursive calls.

User Geno
by
4.3k points