-1

How could I recursively iterate through nodes with reference to a previous node? Expecting output 4,3,2,1 in the example below:

class Node:
    def __init__(self, parent, value):
        self.parent = parent
        self.value = value

    def append(self, value):
        return Node(self, value)

def list(l):
    print(l.value)
    while l.parent is not None:
        list(l.parent)

l = Node(None, 1)
l = l.append(2)
l = l.append(3)
l = l.append(4)
list(l)
Ivan
  • 59
  • 1
  • 9
  • this looks promising at first glance. What does it give you when you run it? (I'm unable to test a Python script at the moment.) – Robin Zigmond Mar 08 '19 at 14:05
  • You can use `self` to pass the current object to another one. For instance : `self.child.parent = self` is a valid piece of code (although you don't have any child attribute in your code, I think it might answer you question) – Joseph Budin Mar 08 '19 at 14:07
  • @RobinZigmond at the moment it is recursively giving me '1' s – Ivan Mar 08 '19 at 14:12

2 Answers2

2

Your class structure already succesfully passes the node's self value to its child node. The problem is your list function. while l.parent is not None: never ends, because nothing in the loop is changing the value of l. Calling list recursively will create a new context where another variable named l has a different value from the first context's l, but this has no effect on the the first l or the first loop. Recursive functions generally do not require an actual loop in order to iterate over the elements of a data structure. Try:

def list(l):
    print(l.value)
    if l.parent is not None:
        list(l.parent)

Or:

def list(l):
    while l is not None:
        print(l.value)
        l = l.parent

(I recommend the latter because the first one will crash with "maximum recursion depth exceeded" if the chain has more than 999 elements)

Result:

4
3
2
1

Bonus style tip: consider naming your function something other than list. In general you should avoid overwriting the names of built-in functions and types.

Kevin
  • 74,910
  • 12
  • 133
  • 166
0

I should vote to close your question for the lack of a clear problem statement, but anyway...

Within an object in Python, how can I pass a reference of my current object

The same way as you'd do with just any object.

to object b of the same class

This is actually irrelevant but anyway...

such that when I call b.parent, I can get back to object a?

class Foo(object):
    def __init__(self, parent=None):
        self.parent = parent

a = Foo()
b = Foo(a)
print(b.parent is a)

Now for the answer to the question you didn't ask, see (and accept) Kevin's answer ;-)

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118