Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

Python Data StructureEnhance your tuples

time to read 1 min | 110 words

Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios.

Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes).

Import namedtuple:

from collections import namedtuple

Create a namedtuple object:

point = namedtuple('3DPoint', 'x y z')
A = point(x=3, y=5, z=6)
print(A)
# 3DPoint(x=3, y=5, z=6)

Access a specific member:

print(A.x)
# 3

Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes:

print(A[0])
# 3

To convert a namedtuple to a dict (Actually an OrderedDict):

print(A._asdict())
#OrderedDict([('x', 3), ('y', 5), ('z', 6)])

Python Data StructureGet more with collections!

time to read 1 min | 97 words

In addition to Python’s built-in data structures (such as tuples, dicts, and lists), a library module called collections provides data structures with additional features, some of which are specializations of the built-in ones.

Import the module:

import collections

Specialized container datatypes are usually dict subclasses or wrappers around other classes like lists, tuples, etc.

Notable implementations are :

  • the Counter class used for counting hashable objects.
  • defaultdict class used as a faster implementation of a specialised dictionary.
  • namedtuple class used for defining a meaning for every position in a tuple, often useful with databases or CSV files.

Python Data StructureQueue in Python - Part 3

time to read 1 min | 91 words

Prioritize your queue

A PriorityQueue is a type of queue imported from the module with the same name.

It uses sort order to decide what to retrieve from it first (your object must have a way of comparing its instances):

import queue

class Rezha(object):
    def __init__(self, priority):
       self.priority = priority
       
    def __lt__(self, other):
       return self.priority > other.priority

q = queue.PriorityQueue()
q.put(Rezha(11))
q.put(Rezha(55))
q.put(Rezha(100))
while not q.empty():
    print(q.get().priority)
# output is 100 / 55 / 11

Having defined the __lt__ method, our PriorityQueue knows now how to sort elements of type Rezha.

Python Data StructureQueue in Python - Part 2

time to read 1 min | 149 words

Double ended queues with deque

The deque class in the collections module makes it easy to create deques or double ended queues. Deques allow you to append and delete elements from both ends more efficiently than in lists.

Import the module:

from collections import deque

Instantiate deque:

d = deque()

Append to right and left:

d.append("b")
d.appendleft("a")
print(d)
# output is: deque(['a', 'b'])

In the same fashion, elements can be deleted (popped) :

d.pop()
d.popleft()
print(d)
# outputs: deque([])

Starting from Python 2.6 you can limit the maximum numbers of elements in a deque passing the maxlen argument to the constructor. If the limit is exceeded, items from the opposite end will be popped as new ones are appended to this end:

d = deque(maxlen=3)
deque([], maxlen=3)
for i in range(4):
    d.append(i)
    print(d)
...
# Output:
deque([0], maxlen=3)
deque([0, 1], maxlen=3)
deque([0, 1, 2], maxlen=3)
deque([1, 2, 3], maxlen=3)

Python Data StructureQueue in Python - Part 1

time to read 1 min | 111 words

Best way to implement a simple queue

A simple list can be easily used and implemented as a queue abstract data structure. A queue implies the first-in, first-out principle.

However, this approach will prove inefficient because inserts and pops from the beginning of a list are slow (all elements need shifting by one).

It’s recommended to implement queues using the collections.deque module as it was designed with fast appends and pops from both ends.

from collections import deque
queue = deque(["a", "b", "c"])
queue.append("d")
queue.append("e")
queue.popleft()
print(queue)
# output is: deque(['c', 'd', 'e'])

A reverse queue can be implemented by opting for appendleft instead of append and pop instead of popleft.

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha