Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用递归函数计数_Python_Python 3.x - Fatal编程技术网

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
行了。但是,回答得好,我比你高:)