Sunday, June 28, 2009

Interesting Python Functions

This post will contain a collection of Python library functions that I found interesting. I will keep adding to the collection as I encounter more interesting functions.

#----------------------------------------------------------------------------
# range() - this function generates a list of numbers
#----------------------------------------------------------------------------

upperBound = 5
range(upperBound) # this generates [0, 1, 2, 3, 4]

lowerBound = 2
range(lowerBound, upperBound) # this generates [2, 3, 4]
range(1, 11, 3) # generates [1, 4, 7, 10].
# range(lowerbound, uppperbound, step)

# an example of range() in action
monthList = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
for i in range(12):
print monthList[i], # prints all the months of the year

#-----------------------------------------------------------------------------------------
# randrange() - generates a random number from a range of numbers
#-----------------------------------------------------------------------------------------

import random # this module is required to use randrange()
random.randrange(6) # generates a random number between 0 to 5 inclusive
random.range(6) + 1 # generates a random number between 1 to 6 inclusive

#--------------------------------------------------------------------------------
# choice() - returns a random element from a sequence
#--------------------------------------------------------------------------------

vowels = ('a','e','i','o','u')
osList = ["linux", "BSD", "UNIX", "NT", "Solaris"]
random.choice(vowels) # randomly selects a vowel
random.choice(osList) # randomly selects an os


Friday, June 26, 2009

A Story of Darkness

Once in a long while, you come across a book that makes you feel like Dostoevsky when he allegedly ran through the streets of St. Petersburg waving a copy of Tolstoy's Anna Karenina and shouting, “This man is God of art!” My own reactions when reading Aravind Adiga's 2008 Man Booker Prize winning debut novel White Tiger was, “This man is a poet of Truth!”

White Tiger is an unflinching look at what the author calls the “Darkness”, the vast underbelly of India where people live on the edge of survival, chaffing under crushing poverty, corrupt institutions, and inherited beliefs and practices that perpetuate their cruel fate. It provides a savage, angry counterpoint to the currently popular narrative of India that has it marching inexorably to unprecedented prosperity and global dominance.

Early in the book, Adiga introduces the theme of the novel in a typically lyrical paragraph:
I am talking of a place in India, at least a third of the country, a fertile place, full of rice fields and wheat fields and ponds in the middle of those fields choked with lotuses and water lilies, and water buffaloes wading through the ponds and chewing on the lotuses and lilies. Those who live in this place call it the Darkness. Please, understand, Your Excellency, that India is two countries in one: an India of Light, and an India of Darkness. The ocean brings light to my country. Every place on the map of India near the ocean is well-off. But the river brings darkness to India – the black river.

Adiga, who did part of his schooling in Sydney, cut his writerly teeth as a correspondent for the Independent, Time and other quality media outlets. This shows in his writing. The narrator, an inhabitant of Darkness who yearns for Light, tells his utterly absorbing story in a language that is a joy to read. Simple, unadorned sentences crackle  with wry humour, sharp wit and sardonic observations that only a uniquely gifted artist can make. Adiga refuses to couch his narrative in Marxist or Manichaen terms, which saves it from being just another banal polemical tract for the underdog.

Unlike some other famous Indian writers, Adiga's voice does not come across as calibrated to appeal to the Western ear. His overriding concern seems to be holding a pitiless mirror to the denizens of the Light and Darkness themselves, and not entertaining distant readers in the cafes of Manhattan or Glebe with fantastic tales of an imagined Orient. Unsentimental, harsh and scathing, Adiga does not absolve the inhabitants of the Darkness themselves from their fate, which he compares to those of butcher-bound roosters trapped in a coop. It is clear to Adiga that the domain of Darkness is not confined to material disparities or geographical boundaries. It subjugates, corrupts and rules the very souls of those who are in its thrall. He has no sympathy for the "human spiders" of the Darkness who, when not wiping tables in cheap roadside tea stalls with dirty rags, occupy themselves with propitiating the absurdly huge array of gods and goddesses of the Darkness, or watching cricket and toothpaste ads on TV.

Monday, June 22, 2009

Tuple, List and Dictionary

This series will feature short notes on Python topics. The idea is to reinforce my learning through "note taking".

Tuple



  • Tuple is just like an array. It is immutable, and holds a sequence of values. However, unlike a C/C++ array, a tuple can store values of mixed types. An example:
      myTuple = ("Python", "PHP", "Ruby", 3.1428, 2009, "Django")


  • Just like a string, a tuple can be indexed, sliced and concatenated with another tuple. When called on a tuple, the len() function returns the total number of elements in the tuple.
    totElements = len(myTuple)
    print totElements # It prints 6



List



  • A list is like a C/C++ dynamic array. Elements can be added, deleted and sorted

  • Just like a tuple, it can store data of mixed types.

  • A list is enclosed in square brackets. For example:
    myList = ["Python", "PHP", "Ruby", "Perl", ('a', 'e', 'i', 'o', 'u')]
    emptyList = [] # this creates an empty list


  • All the tuple operations are applicable to lists


Dictionary



  • A dictionary is like a hash table in other programming languages. It stores data as key-value pairs.

  • A dictionary is enclosed in curly braces.

  • The key must be an immutable data type, i.e. string or tuple. For example,
     
    myDict = {"name" : "Charles Martel", "occupation" : "Palace Mayor, coup leader", "country" : "France"}
    emptyDict = {} # This creates an empty dictionary


Saturday, June 20, 2009

After Missing the Recluse on the Western Mountain

Is there anyone who does not wish to visit a hermitage like the one described in this poem?

AFTER MISSING THE RECLUSE ON THE WESTERN MOUNTAIN
By Qiu Wei
To your hermitage here on the top of the mountain,
I have climbed, without stopping, these ten miles.
I have knocked at your door, and no one answered;
I have peeped into your room, at your seat beside the table.
Perhaps you are out riding in your canopied chair,
Or fishing, more likely, in some autumn pool.
Sorry though I am to be missing you,
You have become my meditation --
The beauty of your grasses, fresh with rain,
And close beside your window the music of your pines.
I take into my being all that I see and hear,
Soothing my senses, quieting my heart;
And though there be neither host nor guest,
Have I not reasoned a visit complete?
... After enough, I have gone down the mountain.
Why should I wait any longer?

Tuesday, June 16, 2009

Finding One's Place in the Sun

Margaret Throsby interviewed internationally renowned British writer and foremost authority in innovation, Sir Ken Robinson, in today's ABC Classic FM Morning Interview. What follows is the gist of what Sir Robinson had to say on imagination, creativity, and finding one's calling in life.

  • Imagination is an agent that brings to mind something that does not exist physically yet

  • Creativity is the practical application of imagination. It produces valuable original ideas

  • Everyone is born with creativity but it gets inhibited by "assembly line" education and adult misconceptions about creativity

  • IQ does not test intelligence. It only reveals the ability to do IQ tests

  • "People feel that if you can't count it, it doesn't count". IQ test is a product of the Victorian bias for the scientific method

  • The question to ask is not how intelligent one is but how one is intelligent

  • Being in one's element means doing something that one has aptitude for. Sir Robinson offered the example of a female snooker player who lost the sense of time when playing snooker

  • Watch children to find out what ticks them in order to find their aptitude

  • The current education system was designed along factory assembly line that churns out finished products. A more appropriate metaphor for education is gardening. Both gardening and education are organic processes that never stop

  • What adults remember about their education are their teachers. Teaching is the heart of education

  • To find your aptitude, do two things: (1) Spend some time with yourself. List the things you enjoy and try to find the commonality in them and (2) Try something you have always wanted to do

  • It is never too late to find one's true calling in life

Sunday, June 14, 2009

A Message to Censor Du Fu At His Office in the Left Court

Way back in my undergraduate days, I printed out 300 Tang Poems, a popular anthology of 310 poems compiled by an 18th century Qing scholar named Sun Zhu. Apart from my fascination with the poetry of the Tang Dynasty (618-907), which presided over China's golden age, the other key motivation for printing out the poems was a substantial, unused print allowance I still happened to have at the end of a semester. What better way to use up the remainder of my print allowance than by printing out Tang poems?

After I got the printouts spiral-bound with a transparent plastic front-cover, I shelved the volume and forgot all about it. It had been gathering dust in my book shelf ever since, until I happened to chance upon it when casting about for something to read on a wintry Sunday evening. Flipping through its pages, I was again struck by the singular beauty of the poems. This has led me to a decision to dip into the collection at random, whenever occasion permits, and, if a piece appeals to me, present it here.

The first offering, by Cen Can, is addressed to Censor Du Fu, who himself comprised, along with Li Bai and Bai Juyi, the poetic triumvirate of the Tang.

A MESSAGE TO CENSOR Du Fu AT HIS OFFICE IN THE LEFT COURT
By Cen Can
Together we officials climbed vermilion steps
To be parted by the purple walls
Our procession, which entered the palace at dawn,
Leaves fragrant now at dusk with imperial incense.
Grey heads may grieve for a fallen flower,
Or blue clouds envy a lilting bird;
But this reign is of heaven, nothing goes wrong,
There have been almost no petitions.

Saturday, June 13, 2009

City2Surf 2009

I will be participating for the second time in Sydney's premier fun run, the City2Surf, that starts at Hyde Park in the heart of the CBD and ends in Bondi Beach. The 14.1 km run will take place on August 9.

My tentative goal for this year is to shave off 9 minutes from last year's time, which was 68' 14'' (The winner, Martin Dent, did it in 41' 12''). It is a big ask. My weekly regime for achieving this goal is as follows:

  • At least two easy runs to enhance my cardiovascular fitness and correct my body posture, transforming my body into a lean, efficient oxygen engine

  • Trim down to my ideal running weight (which is around 56 kg)

  • One fairly difficult hill run to strengthen my leg muscles, i.e. do the round trip circuit from Macquarie Park to Epping train station

  • One interval training to improve my pace

  • One resistance training session to boost my upper and lower body strength

  • Enjoy each training session as much as possible, always keeping in mind Polar's motto: "Listen to your body".