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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With