Kurt Peek - 1 year ago 55

Python Question

Suppose we have a class

`Node`

`class Node(object):`

def __init__(self, data=None, next_node=None, prev_node = None):

self.data = data

self.next = next_node

self.prev = prev_node

and we create an instance

`head`

`head = Node(data=4)`

head.next = Node(data=5)

head.next.next = Node(data=6)

head.prev = Node(data=2)

I'd like to add another node to the doubly-linked list, which I could do by

`head.next.next.next = Node(data=8)`

However, instead of writing ".next" three times, I would like to use a method which takes as input the number of times to call ".next" - that is, something like

`head.next_n_times(3) = Node(data=8)`

Here is what I've tried so far:

`class Node(object):`

def __init__(self, data=None, next_node=None, prev_node = None):

self.data = data

self.next = next_node

self.prev = prev_node

def next_n_times(self, n):

next_node = self.next

for i in range(n-1):

next_node = next_node.next

return next_node

head = Node(data=4)

head.next = Node(data=5)

head.next.next = Node(data=6)

head.prev = Node(data=2)

data = 5

head.next_n_times(3) = Node(data=8)

However, I get the error message

`File "sorted_insert_scratch.py", line 19`

head.next_n_times(5) = Node(data=8)

SyntaxError: can't assign to function call

It seems like the

`next_n_times`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You're trying to implement the append method for the Node class. You can easily do so with recursion:

```
class Node(object):
def __init__(self, data=None, next_node=None, prev_node = None):
self.data = data
self.next = next_node
self.prev = prev_node
def append(self, node):
if self.next:
self.next.append(node)
else:
self.next = node
self.next.prev = self
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**