Useful Python Tricks

Originally inspired from this blog post. But many have been customized and rewritten into an IPython Notebook.

Note: Written for Python 3

Unpacking

a, b, c = 1, 2, 3

a, b, c

(1, 2, 3)
a, b, c = [1, 2, 3]

a, b, c
(1, 2, 3)
a, b, c = (2 * i + 1 for i in range(3))
a, b, c
(1, 3, 5)
a, (b, c), d = [1, (2, 3), 4]

a, b, c, d
(1, 2, 3, 4)

Iterating over list index and value pairs (enumerate)

a = ['Hello', 'world', '!']

for i, x in enumerate(a):
    print('{}: {}'.format(i ...
Read More....

Swift: Bubble Sort

// Sang Han
// An implementation of a bubble party/bubble sort written in swift

import Foundation

func exchange<T>(inout a: T, inout b: T)
{
    let tmp = a
    a = b
    b = tmp
}

func bubbleSort(inout array: [Int]) -> [Int]
{
    let length = array.count

    var count, pos: Int
    for (count=0; count<length-1; count++)
    {
        for (pos=0; pos<(length-count-1); pos++)
        {
            if (array[pos] > array[pos+1]) {
                exchange(&array[pos], &array[pos+1])
            }
        }
    }
    return array
}

func sortMain(arrayLength: Int) -> [Int]
{
    var array: [Int] = []
    for _ in 0..<arrayLength {
        array.append(
            Int(arc4random_uniform(UInt32(arrayLength*100)))
        )
    }
    return bubbleSort(&array)
}
Read More....