Wednesday, February 24, 2016

Ordinal Numbers

In set theory, an ordinal number (or ordinal) is one generalization of the concept of a natural number. With the natural numbers in increasing order {0, 1, 2, …}, each number counts the number of natural numbers that precede it. The ordinals extend this concept beyond the natural numbers by having each ordinal represent the set of all ordinals that are less than it. For instance, the ordinal 2 represents the set {0, 1} and the smallest infinite ordinal, written ω, represents the set of all natural numbers, {0, 1, 2, …}. Some ordinals, like 2, are successor ordinals by virtue of having an immediate predecessor.

Detailed Reading :
https://en.wikipedia.org/wiki/Ordinal_number

What it means to programming
--------------------------------------
Check "man ascii" on linux

>>> ord('$')
36
>>> ord('A')
65
>>> symbols='$¢£¥€¤'
>>> codes = [ord(symbol) for symbol in symbols]
>>> codes
[36, 162, 163, 165, 8364, 164]


Tuesday, February 23, 2016

Python Jargon Reference


ABC : 
Abstract Base Class. Same is Abstract class in C++. It can be used for inheriting the subclass.

accessors : 
Normally getter and setter fucntions for a given attributes. Some refer accessors as getters only and use mutators for setters.

aliasing :
Assigning more than one name to an object. Example a = [1,2,3,4] and b=a. In this case both a and b points to the same object.

binary sequence: 
Generally refers to sequence of binary bytes. The built-in binary sequence types are byte and bytes. Example
>>> key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> print(key)
b'\x13\x00\x00\x00\x08\x00'
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')


callable object:
An object that can be invoked with the call operator (), to return a result or to perform some action. There are seven flavors of callable objects in Python: user-defined functions, built-in functions, built-in methods, instance methods, generator functions, classes, and instances of classes that implement the __call__ special method.

cheese shop:
Original name of the Python Package Index (PyPI), https://cheeseshop.python.org

collection:
Generic term for data structures made of items that can be accessed individually. Some collections can contain objects of arbitrary types (see container) and others only objects of a single atomic type (see flat sequence).
list and bytes are both collections, but list is a container, and bytes is a flat sequence.

constructor:
Informally, the __init__ instance method of a class is called its constructor, because its semantics is similar to that of a Java constructor. However, a fitting name for __init__ is initializer, as it does not actually build the instance, but receives it as its self argument. The constructor term better describes the __new__ class method, which Python calls before __init__, and is responsible for actually creating an instance and returning it. See initializer.

container:
An object that holds references to other objects. Example : List of ints, int is an object by itself.

duck typing:
A form of polymorphism where functions operate on any object that implements the appropriate methods, regardless of their classes or explicit interface declarations.

dunder:
Shortcut to pronounce the names of special methods and attributes that are written with leading and trailing double-underscores (i.e., __len__ is read as “dunder len”).

eager:
An iterable object that builds all its items at once. In Python, a list comprehension is eager.

first-class function:
Any function that is a first-class object in the language (i.e., can be created at runtime, assigned to variables, passed as an argument, and returned as the result of another function). Python functions are first-class functions.

generator function:
A function that has the yield keyword in its body. When invoked, a generator function returns a generator. Example: Function to generate fibnocci numbers.

hashable:
An object is hashable if it has both __hash__ and __eq__ methods, with the constraints that the hash value must never change and if a == b then hash(a) == hash(b) must also be True. Most immutable built-in types are hashable,
but a tuple is only hashable if every one of its items is also hashable.
>>> a=10
>>> b=a
>>> a==b
True
>>> hash(a)==hash(b)
True
>>> b=30
>>> hash(a)==hash(b)
False
>>>
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

weak reference:
A special kind of object reference that does not increase the referent object reference count. Weak references are created with one of the functions and data structures in the weakref module.

higher-order function:
A function that takes another function as argument, like sorted, map, and filter, or a function that returns a function as result, as Python decorators do.

iterable:
Any object from which the iter built-in function can obtain an iterator. An iterable object works as the source of items in for loops, comprehensions, and tuple unpacking. Objects implementing an __iter__ method returning an
iterator are iterable. Sequences are always iterable; other objects implementing a __getitem__ method may also be iterable.

iterator:
Any object that implements the __next__ no-argument method, which returns the next item in a series, or raises StopIteration when there are no more items. Python iterators also implement the __iter__ method so they are also
iterable. Classic iterators, according to the original design pattern, return items from a collection. A generator is also an iterator, but it’s more flexible. See generator.

metaclass:
A class whose instances are classes. By default, Python classes are instances of type, for example, type(int) is the class type, therefore type is a metaclass. User-defined metaclasses can be created by subclassing type.

refcount:
The reference counter that each CPython object keeps internally in order to determine when it can be destroyed by the garbage collector.

referent:
The object that is the target of a reference. This term is most often used to discuss weak references.

sequence:
Generic name for any iterable data structure with a known size (e.g., len(s)) and allowing item access via 0-based integer indexes (e.g., s[0]). The word sequence has been part of the Python jargon from the start, but only with
Python 2.6 was it formalized as an abstract class in collections.abc.Sequence.

serialization:
Converting an object from its in-memory structure to a binary or text-oriented format for storage or transmission, in a way that allows the future reconstruction of a clone of the object on the same system or on a different one.
The pickle module supports serialization of arbitrary Python objects to a binary format.

singleton:
An object that is the only existing instance of a class—usually not by accident but because the class is designed to prevent creation of more than one instance. There is also a design pattern named Singleton, which is a recipe for coding such classes. The None object is a singleton in Python.

strong reference:
A reference that keeps an object alive in Python. Contrast with weak reference.

view:
Python 3 views are special data structures returned by the dict methods .keys(), .values(), and .items(), providing a dynamic view into the dict keys and values without data duplication, which occurs in Python 2 where those methods
return lists. All dict views are iterable and support the in operator. In addition, if the items referenced by the view are all hashable, then the view also implements the collections.abc.Set interface. This is the case for all views returned by the .keys() method, and for views returned by .items() when the values are also hashable.

Sunday, February 21, 2016

Slicing and List Comprehension in Python

Slicing in python.

This lets you work on specific portions of the given sequence(list/str/bytes). Read it as Slice a pound of bread and give half to brother and keep half for yourself.

Slicing can be extended to any Python class that implements the __getitem__ and __setitem__ special methods.

Syntax :

gucalist[start:end], where start is inclusive and end is exclusive.

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print('First four:', a[:4])
print('Last four: ', a[-4:])
print('Middle two:', a[3:-3])

>>>
First four: ['a', 'b', 'c', 'd']
Last four:  ['e', 'f', 'g', 'h']
Middle two: ['d', 'e']


Starting from the first, zero is understood.
a[:5] = a[0:5]

Slicing till the end,   "end" is understood.

a[5:] = a[5:len(a)]

Playing with negative index

a[:]      # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[:5]     # ['a', 'b', 'c', 'd', 'e']
a[:-1]    # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a[4:]     #                     ['e', 'f', 'g', 'h']
a[-3:]    #                          ['f', 'g', 'h']
a[2:5]    #           ['c', 'd', 'e']
a[2:-1]   #           ['c', 'd', 'e', 'f', 'g']
a[-3:-1]  #                          ['f', 'g']


NOTES :
1. Slicing operation returns the whole new object.. Keeping the original as it is.
b = a[4:]
print('Before:   ', b)
b[1] = 99
print('After:    ', b)
print('No change:', a)

>>>
Before:    ['e', 'f', 'g', 'h']
After:     ['e', 99, 'g', 'h']
No change: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


List Comprehension 
===================
Compute the sqaure of each numbers in the list

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [x**2 for x in a]
print(squares)

>>>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

what if you wanted only the squares of the numbers in the given list, which are divisible by 3

squares = [x**2 for x in a if x%3==0]

List comprehension for dicts

>>> g_fam= {'ravi':33, 'rash':31, 'tan':6, 'sam':1}
>>> age_dict = {age:name for name, age in g_fam.items()}
>>> print(age_dict)
{1: 'sam', 33: 'ravi', 6: 'tan', 31: 'rash'}
>>>


More than two expressions in list comprehension

Flatting the matrix into a single list

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat)

NOTE : These expressions run in the order provided from left to right. So in this case take each row first and loop over it.

Multiple loops is replicating the two-level deep layout of the input list. For example, say you want to square the value in each cell of a two-dimensional matrix. This expression is noisier because of the extra [] characters, but it’s still easy to read.

squared = [[x**2 for x in row] for row in matrix]
print(squared)

>>>
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]


multiple if conditions in a list comprehension

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
c = [x*x for x in a if x > 4 and x % 2 == 0] # get the squares of each if it even and greater than 4.



Tuesday, February 2, 2016

Define/Encode/Serialize

Once upon a time, packing the structure construct defined in C was considered as an art of programming. Literally all the signalling protocol simulators I worked with had this one cryptic piece of packing and unpacking the message. 

Now a days it is much more convenient with all the different efficient methods. In fact most of them come with the underlying RPC mechanism too. Below are some, which can be used.  

1. Google Protocol Buffers. 
https://developers.google.com/protocol-buffers/docs/overview

2. Facebook Thrift 
http://thrift-tutorial.readthedocs.org/en/latest/intro.html

3. Cap'n Proto 
https://capnproto.org/

For XML lovers, I am sure you know where and what to look for :)