Python 用递归函数计数
我想构建一个递归函数,它采用三元字母树并计算树中大写字母的数量。我知道这对许多有经验的程序员来说是一项简单的任务,但我不知道该怎么做。以下是我到目前为止的情况:Python 用递归函数计数,python,python-3.x,Python,Python 3.x,我想构建一个递归函数,它采用三元字母树并计算树中大写字母的数量。我知道这对许多有经验的程序员来说是一项简单的任务,但我不知道该怎么做。以下是我到目前为止的情况: def count_upper(tlt, ): """returns the number of uppercase letters in a ternary letter tree tlt -> number""" if i.isupper(): return count_upper(tlt, ) e
def count_upper(tlt, ):
"""returns the number of uppercase letters in a ternary letter tree
tlt -> number"""
if i.isupper():
return count_upper(tlt, )
else:
return 0
如果可以,请提供帮助…我假设TLT具有类型为
Node
的节点,每个节点都是具有属性left
、mid
和right
的对象,其中每个属性都可以为none(表示没有子级)。这些成员也属于Node
类型。此外,每个节点
都有一个名为value
的成员,其类型为str
。根据这个假设,这个函数应该做您想要做的事情
def count_upper(node):
children = [node.left, node.mid, node.right]
child_count = 0
for child in children:
if child is not None:
child_count += count_upper(child)
return child_count + 1 if node.value.isupper() else child_count
要计算树中大写字母的数量,请按如下方式调用函数:
count\u upper(root)
您是如何创建tlt
?类似('a'('B','c'))@billynchp请包含一些显示如何创建tlt
的代码。三元字母树(tlt)将由用户输入。。。我刚才用了一个@BillLynch的例子,变量I
?这是递归的。:)还是你的意思是重复?你是对的。我不允许使用for循环。。。我看看是否可以解决这个问题。为孩子们使用for
循环的替代方法是分别调用每个孩子的函数。重复可以被循环替换的代码行是糟糕的编程。不允许使用for
循环的确切含义是什么?编写最后一行的更优雅的方法是返回child\u count+int(node.value.isupper())
,for循环可以重新编写为child\u count=sum(如果child不是None,则child中的child可以使用count\u upper(child))
然后您就不需要子项计数=0
行了。但是,回答得好,我比你高:)