0
['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]]

This is my list and I need to iterate over it in a specific manner. The output for the following should be :-

P -> Q 
Q -> R
R -> S U
S -> T
U -> V

I tried following thing:-

def traverse_mystructure(tree):
    queue = [tree]

    for list in tree:
        print list
        traverse_mystructure(list);

I am not able to get this kind of output with the above.Is it possible to obtain this kind of output ?

4
  • Why do you need a queue, that's normally use for an iterative solution vs. recursive. BTW: don't use list as a variable name - it hides the python list type. Breadth first print will be simpler iteratively (queue). Commented Nov 25, 2016 at 4:42
  • You also need to handle the base case when doing recursion. The base case here is when tree is an empty list Commented Nov 25, 2016 at 4:46
  • I assume, your class mate asked the same question here today. Commented Nov 25, 2016 at 4:50
  • @schwobaseggl don't know about it.. Commented Nov 25, 2016 at 4:51

1 Answer 1

1

I have done this roughly by assuming only the given pattern in your question.

inputList = ['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]]

print inputList

def printSomeMore(newList):
    output = ""
    for sublist in newList:
        if (len(sublist) == 1):
            output = sublist + " ->"
        else:
            output = output + " " + sublist[0]
    return output

def printMyList(myList):
    for each in myList:
        if str(myList[0]) == str(each):
            if (len(myList) == 2):
                print each, "->", myList[-1][0]
            if (len(myList) > 2):
                value = printSomeMore(myList)
                print value
        if str(type(each)) == "<type 'list'>":
            printMyList(each)

printMyList(inputList)

The output that I get from this.

['P', ['Q', ['R', ['S', 'T'], ['U', 'V']]]]
P -> Q
Q -> R
R -> S U
S -> T
U -> V
Sign up to request clarification or add additional context in comments.

Comments

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.