Python 递归调用函数并计算成员数。但是它有一个bug!你能发现问题并解决它吗?
我想应该是这样的:Python 递归调用函数并计算成员数。但是它有一个bug!你能发现问题并解决它吗?,python,python-3.x,recursion,global-variables,local,Python,Python 3.x,Recursion,Global Variables,Local,我想应该是这样的: def count_users(group): count = 0 for member in get_members(group): count += 1 if is_group(member): count += count_users(member) return count 如果你不把组看作用户。 似乎没有其他bug或其他任何东西。如果问题仍然存在,您可能还应该发布项目其他部分的代码。d
def count_users(group):
count = 0
for member in get_members(group):
count += 1
if is_group(member):
count += count_users(member)
return count
如果你不把组看作用户。
似乎没有其他bug或其他任何东西。如果问题仍然存在,您可能还应该发布项目其他部分的代码。def count\u usersgroup:def count_users(group):
count = 0
for member in get_members(group):
if is_group(member):
count += count_users(member)
else
count += 1
return count
计数=0
对于get_membersgroup中的成员:
计数+=1
如果是集团成员:
count+=count\u用户成员-1
返回计数
如果一个成员是一个组,则添加该组中的成员数-1,因为u之前添加了1,就好像它是一个成员,但它不是,这是一组代码:问你这个问题的人都想知道你是否可以。这似乎是一个家庭作业,只为你而不是其他人解决。我认为这个问题可以用If和else语句解决。请不要只发布代码作为答案,但也要解释代码的作用以及它如何解决问题。带有解释的答案通常更有帮助,质量更好,更容易吸引选票
def count_users(group):
count = 0
for member in get_members(group):
count += 1 #it is also increasing when the member is a group
if is_group(member):
**count -= 1** #if the member is a group, decrease 1 which was increased previously
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 #it is also increasing when the member is a group
if is_group(member):
**count -= 1** #if the member is a group, decrease 1 which was increased previously
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):
if is_group(member):
count += count_users(member)
else:
count += 1 #Moved from the outside of the "IF" block and put into the ELSE
#part of the IF statement. This removes the double counting.
return count
print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18