atultherajput
atultherajput

Reputation: 175

Why this code is not able call function inside another function in python

I am trying to implement Singly Linked List in Python. This is my _Node class:

#!/usr/bin/env python3
class _Node:
    """Node class to create new nodes"""
    def __init__(self, data=None, next=None):
        """Construction of node"""
        self._data = data
        self._next = next

I have removed push(), pop() and other methods from this code sample. They all are working.

class LinkedList:
      """Singly Linked List implementation for storage"""
    def __init__(self):
        """Construction of Linked List"""
        self._head = None
        self._size = 0

    def __len__(self):
        """Return length of linked list."""
        self._count = 0
        self._current = self._head
        while self._current:
            self._count += 1
            self._current = self._current._next
        return self._count

    def value_at(self, index):
        """Return Value at given index"""
        self._current = self._head
        self._index = index
        count = ans = 0
        while count<= self._index:
            if self._current == None:
               return "List is empty."
            ans = self._current._data
            self._current = self._current._next
            count += 1
        return ans

    def value_n_from_end(self, n):
        """Get value of nth element starting from end"""
        self.n=n
        self.n = int(self.__len__() - self.n -1)
        print(self.n) #print value as expected
        self.value_at(self.n)

Now my problem is that i can get value from value_at() but unable to get value from value_n_from_end() outside the class. Input:-

l = LinkedList()
print(l)
print(l.__len__())
print(l.value_at(1))
print(l.value_n_from_end(2))

Output:-

5-> 3-> 4-> 6->  //My Linked List
4                //Length of linked list
3                //Value return by l.value_at(1)
1                //This is the value which i want to pass in self.value_at(self.n)
None             //This is returned from (l.value_n_from_end(2))

Value of l.value_n_from_end(2) should be same as l.value_at(1) i.e. 3. But i am missing something.

Upvotes: 1

Views: 271

Answers (1)

tupui
tupui

Reputation: 6528

The value_n_from_end does not return anything. You should write:

return self.value_at(self.n)

Indeed, self.value_at(self.n) returns what you want in the function value_n_from_end but then you have to get it back to you by using a return statement. Otherwise it is bound to the function namespace.

Upvotes: 1

Related Questions