Pythonic ways

What is bool?

Implicit boolean value of a empty list

a = []
if not a:
    print('a is empty')

List

[] slicing notation

Slicing with a[start:end]

it will return an list of elem from a[start] till a[end – 1]. If start > end then return an empty string. Very good to know for boundary checks. Also works for string. We can omit both start and end and that will return a copy of the whole array.

To make a copy of 2d array

copy_a = [row[:] for row in origin_a]

Negative index

start or and can be negative. It will count from the end. a[-1] is the last element a[-2:] will return the last two element. a[:-2] everything except the last two

Negative steps:

a[::-1] # all items in the array, reversed a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items, reversed a[-3::-1] # everything except the last two items, reversed

a[1::-1] means start at index 1 and go till 0, where 0 is right before the end. a[:-3:-1] means we will start from 0 and go back till right before the third last(so the last two reversed).

[ : : ]

These two links are really helpful Stackoverflow Yeah we don’t code anymore. Just move codes around

Copy list

List is mutable so through pass by assignment, a = b will just pass b’s handle to a. If we want to copy, we can use a = b[:] where b[:] will return a copy of the whole list

String

strip all chars

Using join

First we need to find all possible punctuation:

import string
exclude = set(string.punctuation)

set will create element for each and every char in string.punctuation.

Then we will remake the given string using join.

new_s = ''.join(c for c in old_str if c not in exclude)

We will join an empty string with all char in the old string that’s not in exlude (aka not punctuation)

We can remove whitespace as well by adding and c != ‘ ‘.

Using translate

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

This use translate and will perform a row string operation in C. Not gonna beat it in spead.

Reverse a string (array)

s = s[::-1]

We lost cmp in python3

This is because of PEP207. They proposed rich comparison; They are <, >, <=, >=, ==, !=, which associates to lt, gt, le, ge, eq, and ne. cmp is no longer used in it.
SAD NEWS

Now when you want to pass a comparison to sort you might have to define your own.
The 2.7 handbook says:

cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

So we can write:

def my_cmp(x,y):
    (a > b) - (a < b)

This is actually the official work around in the documentation.FOR REAL
It will return 1 if a > b, -1 if a < b and 0 if a == b

Iter through dictionary in Python

I am still doing the Google foo-bar problem and need more dictionary operations. I have always doubt the way I iterate through a dictionary: first store a key in a list then iterate through the dictionary in a for loop, is really bad and I want to find a better way. It is called item().

An example:

“””python

knights = {‘gallahad’: ‘the pure’, ‘robin’: ‘the brave’} for k, v in knights.items(): … print(k, v) … gallahad the pure robin the brave “””

.item() generates a list of tuple. This is potentially very memory consuming but would be very fast for loop up. There is another method called iteritem() in python3 and it will return a generator. It is faster if you only want to iterate since the whole list is never generated.

Sets in Python

Ran into a problem that needed set as a tool to solve it.

What is a set?

A set is a collection of unordered unique objects.

What are the common operations

Intersection, union subset and so on.

Operation     Result
len(s)      number of elements in set s (cardinality)
x in s      test x for membership in s
x not in s      test x for non-membership in s
s.issubset(t)     test whether every element in s is in t
s.issuperset(t)  test whether every element in t is in s
s.union(t)     new set with elements from both s and t
s.intersection(t)      new set with elements common to s and t
s.difference(t)    new set with elements in s but not in t
s.symmetric_difference(t)     new set with elements in either s or t but not both
s.copy()        new set with a shallow copy of s

What it can’t do

Slicing, indexing and other things that associated with orders.

Hashing?

Can we hash sets?

No we can not hash sets since set is mutable.So set doesn’t have the hash function in its class.

What if we want to have a set of set?

We will talk about immutable Set soon. It is a set that’s immutable therefore we can subsequently use it as a object to hash

Set classes implementation

It is implemented using a dictionary so it requires objects in the set to have hash() and eq()

Immutable set

As the name indicate, it is a set that doesn’t change and subsequently has a hash() function.