Python – TechEuler

Python – TechEulerUnOrdered Linked list – Prepend, Append, Insert At, Reverse, Remove, SearchUse of __slots__ in Python ClassUsage of Underscores before and after function name in Python

Warning: Cannot modify header information – headers already sent by (output started at /home/manikandancsea/public_html/index.php:4) in /home/manikandancsea/public_html/wp-includes/feed-rss2.php on line 8
http://www.techeuler.com A Tech blog for nerds Thu, 28 Jul 2016 02:50:56 +0000 en hourly 1 https://wordpress.org/?v=4.5.3 http://www.techeuler.com/python/unordered-linked-list-prepend-append-insert-at-reverse/ http://www.techeuler.com/python/unordered-linked-list-prepend-append-insert-at-reverse/#respond Thu, 28 Jul 2016 02:44:30 +0000

http://www.techeuler.com/?p=29

In order to implement an unordered linked list we need to construct linked list which contains Node class, a building block for constructing linked list

Linked List

class Node(object):
    def __init__(self, item):
        self.data = item
        self.next = None
    
    def setNext(self, newnext):
        self.next = newnext
    
    def getNext(self):
        return self.next
    
    def setData(self, item):
        self.data = item
    
    def getData(self):
        return self.data


class UnOrderedLinkedList(object):
    
    def __init__(self):
        self.head = None
        self.tail = None
    
    def prepend(self, data):
        n = Node(data)
        n.setNext(self.head)
        self.head = n
        if n.getNext() == None:
            self.tail = n
    
    def append(self, data):
        n = Node(data)
        self.tail.setNext(n)
        self.tail = n
    
    def insertAfter(self, item, data):
        n = Node(data)
        found = False
        current = self.head
        while not found:
            if current.getData() == item:
                n.setNext(current.getNext())
                current.setNext(n)
                found = True
            else:
                current = current.getNext()
                
    def search(self, item):
        found = False
        current = self.head
        while current != None and not found:
            if current.getData() == item:
                found = True
            else:
                current = current.getNext()
        return found

    def size(self):
        current = self.head
        size = 0
        while current != None:
            size += 1
            current = current.getNext()
        return size

    def remove(self, item):
        current = self.head
        found = False
        while not found:
            if current.getData() == item:
                found = True
            else:
                previous = current
                current = current.getNext()
        if previous == None:
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

    def printList(self):
        current = self.head
        while current != None:
            print current.getData() , 'n|'
            current = current.getNext()

    def reverse(self):
        current = self.head
        previous = None
        while current:
            next = current.getNext()
            current.setNext(previous)
            previous = current
            current = next
        self.head = previous
        return self.printList()

]]>
http://www.techeuler.com/python/unordered-linked-list-prepend-append-insert-at-reverse/feed/ 0 http://www.techeuler.com/python/use-of-__slots__-in-python-class/ http://www.techeuler.com/python/use-of-__slots__-in-python-class/#comments Tue, 31 May 2016 17:07:42 +0000

http://www.techeuler.com/?p=22

__slots__

Slots are predominantly used for avoiding dynamically created attributes. It is used to save memory spaces in objects. Instead of dynamically created objects at any time, there is a static structure that does not allow after the initial creation. You would want to use __slots__ if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__ only exists as a memory optimization tool. This reduces the overhead of the dict of every object that uses slots. Let us see an example with and without using slots:

Python class without __slots__

>>> class A(object):
...     pass
... 
>>> a = A()
>>> a.x = 66
>>> a.y = "dynamically created attribute"

The dictionary containing the attributes of “a” can be accessed like this:

>>> a.__dict__
{'y': 'dynamically created attribute', 'x': 66}

Python class with __slots__


    When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name __slots__. The list has to contain all the attributes, you want to use. We demonstrate this in the following class, in which the slots list contains only the name for an attribute “val”.

>>>class S(object):
...
...    __slots__ = ['val']
...
...    def __init__(self, v):
...        self.val = v
...
>>>x = S(42)
>>>print(x.val)
>>>x.new = "not possible"

Warning:Unfortunately, there is a downside to using slots. It�™s not great for code maintenance, and it really only saves you when you have thousands of instances. Therefore, don�™t prematurely optimize and use this everywhere!

If you’re using __slots__ under PyPy, Read this on Stackoverflow before you proceed.

References:

  1. https://docs.python.org/2/reference/datamodel.html#slots
  2. http://www.python-course.eu/python3_slots.php
  3. http://stackoverflow.com/questions/472000/python-slots

]]>
http://www.techeuler.com/python/use-of-__slots__-in-python-class/feed/ 1 http://www.techeuler.com/python/usage-of-underscores-before-and-after-function-name-in-python/ http://www.techeuler.com/python/usage-of-underscores-before-and-after-function-name-in-python/#comments Tue, 31 May 2016 15:52:41 +0000

http://www.techeuler.com/?p=6

We often find underscore(s) before and after the function name in python while reading the source code. Do you know why and where it has to be used?

I’ll impart the use of underscore in Python’s function name. There are three possibilities of underscore occurred in function name, one underscore at the beginning(_get_name), two underscores at the beginning(__generate), and two underscores at the either side of function(__len__)

One underscore at the beginning:

Python doesn’t have real private methods, so one underline in the start of a method or attribute means you shouldn’t access this method because it not the part of API.

classBaseForm(StrAndUnicode):
    def _get_errors(self):
        "Returns an ErrorDict for the data provided for the form"
        if self._errors isNone:
            self.full_clean()
        return self._errors

    errors = property(_get_errors)

_get_errors, is “private”, so you shouldn’t access outside the class.

Two underscores in the beginning:

It makes a lot of confusion. It should not be used to create a private method. It should be used to avoid your method to be overridden by a subclass.

class A(object):
    def __test(self):
        print"I'm test method in class A"
    def test(self):
        self.__test()

class B(A):
    def __test(self):
        print"I'm test method in class B"
a = A()
print a.test() # Output: I'm test method in class A
b = B()
print b.test()  # Output: I'm test method in class A

As we have seen, b.test() didn’t call B.__test() methods, as we could expect. Basically it is the correct behavior for __. So, when you create a method starting with __ it means that you don’t want anyone to override it, it will be accessible only from inside the class where it was defined.

Two underlines in the beginning and in the end:

When we see a method like __this__, don’t call it. Because it means it’s a method which Python calls, not by you. Let’s take a look:

>>> name ="test string"
>>> name.__len__()
11
>>> len(name)
11

>>> number =10
>>> number.__add__(40)
50
>>> number +50
60

There is always an operator or native function which calls these magic methods. Sometimes it’s just a hook Python calls in specific situations. For example __init__() is called when the object is created. __new__() is called to build the instance. For more details PEP-8 guide will help more.

]]>
http://www.techeuler.com/python/usage-of-underscores-before-and-after-function-name-in-python/feed/ 1