0

I want to build a RECURSIVE function that takes a ternary letter tree and counts the number of uppercase letters in the tree. I know this is a simple task to many experienced programmers, but I cannot figure out what to do. Here is what I have so far:

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

Help if you can...

6
  • How did you create tlt? Commented Mar 25, 2015 at 23:11
  • something like ('a'('B','c')) @BillLynch Commented Mar 25, 2015 at 23:12
  • Please include some code showing how you create tlt. Commented Mar 25, 2015 at 23:14
  • the ternary letter tree (tlt) will be inputted by the user... I just used an example @BillLynch Commented Mar 25, 2015 at 23:15
  • What is the variable i? Commented Mar 25, 2015 at 23:18

1 Answer 1

2

I am assuming that the TLT has nodes of type Node each of which is an object that has the properties left, mid and right, where each of these properties could be none (indicating no child). These members are of also of type Node. In addition, each Node has a member called value that is of type str. With this assumption, this function should do what you want.

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

To count the number of uppercase letters in a tree, invoke the function as thus: count_upper(root)

Sign up to request clarification or add additional context in comments.

4 Comments

This IS recursive. :) Or did you mean iterative?
youre right. I'm not allowed to use a for loop... ill see if i can work around that
The alternative to using a for loop for the children is to invoke the function on each of them individually. Repeating lines of code that can be replaced by a loop is poor programming. What exactly do you mean by not being allowed to use a for loop?
A more elegant way of writing the last line would be return child_count + int(node.value.isupper()) and the for loop can be re-written as child_count = sum(count_upper(child) for child in children if child is not None) and then you don't need the child_count = 0 line. But, good answer, I upvoted you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.