leonardo

View: Recent Entries. View: Archive. View: Friends. View: Profile. View: Website (My Website). October 26th, 2008 Tags: d language, python Security: Subject: Why I like D language Time: 02:28 am

http://confusion.tweakblogs.net/blog/1141/an-example-of-why-i-like-python.html



/>During the past week, the Dutch alternative radiostation Kink FM aired the Kink 1300: the top 1300 songs their listeners wanted to hear. I was interested in finding the most popular bands in the list and wrote a small Python program to do just that.<

The list:

http://www.kinkfm.com/kink1300



My Python version without REs:

from collections import defaultdict bands2titles = defaultdict(list) for line in open("songs.txt"): band, title = line.split("-", 1) band = band.split(".", 1)[1].strip() bands2titles[band].append(title.strip()) pairs = sorted(bands2titles.iteritems(), key=lambda (b,t): (-len(t), b)) for band, titles in pairs: print len(titles), band+":", ", ".join(sorted(titles))

Python version with REs:

import re, collections bands2titles = collections.defaultdict(list) for line in open("songs.txt"): artist, song = re.search("\d+\. (.+?) - (.+)", line).groups() bands2titles[artist].append(song) pairs = sorted(bands2titles.iteritems(), key=lambda (b,t): (-len(t), b)) for band, titles in pairs: print len(titles), band+":", ", ".join(sorted(titles))

My D 1 version using my libs (and Phobos), it's quite similar to the Python version:

import d.all, std.regexp, std.string; void main() { string[][string] aa; foreach (line; xfile("songs.txt")) { auto mobj = search(line, r"\d+\. (.+?) - (.+)"); aa[mobj.match(1)] ~= mobj.match(2); } auto bands = sortedAA(aa, (string b, string[] t){return record(-len(t), b);}); foreach (b; bands) putr(len(aa[b]), " ", b, ": ", sorted(aa[b]).join(", ")); } The D version uses xfile() that yields the lines (strings) lazily, with newline.

search() comes from the std.regexp.

sortedAA sorts with an associative array according to the given key function. The given lambda uses record() that builds a struct on the fly, inferring its fields, and it contains universal comparing, hashing, joining, etc, indexing, methods, it can be used almost as a Python tuple.

array.join() comes from std.string. A very simple problem:/>During the past week, the Dutch alternative radiostation Kink FM aired the Kink 1300: the top 1300 songs their listeners wanted to hear. I was interested in finding the most popular bands in the list and wrote a small Python program to do just that. comments: Leave a comment

leonardo

View: Recent Entries. View: Archive. View: Friends. View: Profile. View: Website (My Website).