Posts

Showing posts with the label algorithms

Python - A good introductory programming language?

First a little experiment. The other day, I needed to count words in a string. One straightforward method for this is to break the string into tokens and count them: def count_words_split(sen): return len(sen.split()) This is nice since split automatically takes care of multiple consecutive spaces if present. However in my case all the words were guaranteed to be separated by 1 space only. So following should get the job done with a little less work: def count_words_count(sen): return sen.count(' ') + 1 This is essentially a single pass over the string with no need to create an intermediate list of strings and so should run faster. Surprisingly, on Python 2.5, the first method is twice as fast as the second one. I have no idea why. However sanity is restored on Python 2.6 and the second version is not only faster but also gets better with increasing size of input. This got me thinking about a good introductory programming language. I learned programming with C and ...