Kurt Peek Kurt Peek - 3 months ago 9
Python Question

How to set a class attribute a specified number of times in Python

Suppose we have a class

Node
which is initialized as follows:

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
as follows:

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)
which would have the same effect. How could I achieve this?

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
method works as a 'getter', but not as a 'setter'. How can I make it work as a 'setter'?

Answer

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
Comments