Python递归函数计数用户

ssm49v7z  于 12个月前  发布在  Python
关注(0)|答案(6)|浏览(138)

count_users函数递归地计算公司系统中属于某个组的用户数量,方法是遍历一个组的每个成员,如果其中一个成员是一个组,则递归地调用该函数并计算成员。但是它有一个bug!你能发现问题并修复它吗?

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

字符串

8i9zcol2

8i9zcol21#

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

字符串

hujrc8aj

hujrc8aj2#

问题出在for循环中。目前,对于组中的每个“成员”,计数增加1,即使该成员本身就是一个组。相反,将该行移动到if is_group(member)之后的一个新的else分支中,因此如果member是一个组,则只增加成员数,如果member不是一个组,则只增加1。

nkkqxpd9

nkkqxpd93#

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

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18

字符串

sulc1iza

sulc1iza4#

下面是正确的解决方案:

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

字符串
print(count_users("sales")) #应该是3
print(count_users("engineering")) #应该是8
print(count_users("everyone")) #应该是18

41ik7eoe

41ik7eoe5#

def count_users(group):
  count = 0
  for member in get_members(group):
    count += 1
    if is_group(member):
      count += count_users(member)
      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

字符串

count -= 1意味着一个假设的成员,结果是一个组,只需要从count变量中删除。

zsohkypk

zsohkypk6#

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

字符串

相关问题