Lightly Seared On The Reality Grill

Random expat geekery from The Low Countries

Browsing Posts tagged Python

Looptastic

No comments

While playing around with Dicetastic earlier this week, I started to feel the need to optionally loop the program so that I didn’t have to repeatedly re-execute the command. This is now implemented and the latest and greatest version has been committed to GitHub.

The changes are documented on the Dicetastic page but the shorter version is that if you start Dicetastic with a -l or --loop, it will loop until you attempt to roll 0d0.

As part of this, I have added two methods to the Dicelib library, get_sides and get_count. They are documented, but their usage should be obvious.

flattr this!

It was in the middle of last year that I implemented what I rather ambitiously referred to as a wallpaper switcher for Gnome 2. What Macsen’s Transitioning Background does is generate an XML file based on the images in a selected folder and then let the Gnome background switcher handle the rest.

With the switch to Gnome 3 this functionality is no longer supported. At least, not as far as I can tell.

I do still like the idea of using an XML file to control the background and have been toying with the idea of knocking together myself. As a first step towards this, I have tidied up some of the code.

The latest version of the source can be found on GitHub. The generated XML can be used to power a transitioning background in Gnome 2 and – if I ever find the time – I will start knocking together something that will work under Gnome 3.

flattr this!

I mentioned yesterday that I had been playing around with Pylint and slowly cleaning up my existing code. The first result of this can now be seen online – I have just just committed the cleaned up code for Dicetastic to my GitHub repository.

flattr this!

I spent most of yesterday evening playing around with Pylint, a static analysis tool that reads your source code and looks for common mistakes. I found a lot.

You can find Pylint in the Sabayon repositories, so it can be installed with a simple equo install pylint and then you’re off.

Running Pylint over a random module, the first thing that surprised me was just how much information the application provides. The first thing it gives you is a line-by-line list of issues – this tells you exactly what problems your code has, and where these problems are. In my case, the vast majority of these were Convention and Warning types, indicating that I really do need to clean up my Python coding style.

It then provides a number of reports which gives you a stack of metrics by which to measure the quality of your code. These were interesting, but would probably be more useful if I was running Pylint over a larger source file.

The approach I found most useful was to go through the list of issues and, for the obvious ones, just fix them. For less obvious issues, I found myself going to the Python documentation to understand why the issue had been raised and what was wrong with my existing approach.

There is a lot of documentation available for Pylint and a goodly set of configuration options. I have looked at neither so far because the reports that it generates are so self-explanatory that it is very easy to jump right in.

This is a tool I can see myself using for a long time to come and, as codebases grow, this is a tool that will become increasingly useful.

flattr this!

Just a quick note to confirm that a Dicetastic project page has now been added to this site.

I do, at some point, want to put a graphical front end on this but I tend to find GUI programming annoyingly fiddly so I won’t make any promises as to when this might appear.

flattr this!

When I started trying to teach myself to program in Python, one of the first applications I wrote (apart from the online and printed exercises I could find) was a simple dice rolling application. For a selected number of dice, it would calculate the rolls and return them as a list.

As time went on I tinkered with this a bit more, separating the guts of the application from the (admittedly simple) terminal interface. I have now cleaned this up a bit and put it on GitHub. Dicetastic consists of a library and a simple program that uses the library.

I’m not convinced that anyone will actually find this useful, but I do know that it isn’t doing anything just sitting on my hard drive.

I will put together a project page on this site for the application (probably tomorrow) but, for now, the code is up and you are welcome to take a look.

flattr this!

Also known as: Project Euler problem 15

Also known as: A week to understand, a minute to implement.

The problem:

Starting in the top left corner of a 2 x 2 grid, there are 6 routes (without backtracking) to the bottom right corner.

How many routes are there through a 20 x 20 grid?

To start with the simple observation first: Any route through an m x m grid can be expressed as a sequence of Rs and Ds where R is right and D is down (the without backtracking condition ensures that you can’t go left or up – this simplifies things somewhat).

The second observation is that each route must be exactly 2m steps long (m steps to the right and m steps down).

So the problem that needs to be solved is: How many ways can you combine m Rs and m Ds?

It turns out that this is a combination problem which Wikipedia handily defines as a way of selecting several things out of a larger group, where order does not matter. The larger group, in this case, is all 2m steps and the several things you want to select are the k possible combinations of R (or D). The Ds (or Rs) don’t matter because you know that they have to populate the m remaining slots in the path.

A k-combination of a set S is a subset of k distinct elements of S. If the set has n elements the number of k-combinations can be expressed as n! / k!(n - k)! as long as k<=n.

Implementing this was a doddle and, for bonus points, my solution should work for any rectangular grid.

flattr this!

Also known as Project Euler Problem 12.

This is the first one that has proved to be a bit of a challenge for me, and one that forced me both to do a bit of research and to take a look at the efficiency of some of my functions.

First the problem:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Obviously a brute-force approach is not going to work in this case. Since I already had a function for generating prime factors, which I developed for Problem 3, I started thinking about whether it was possible to calculate the total number of divisors of a number based on its prime factors.

It turns out that it is.

The factorisation of a number can be expressed as: P1^F1 * P2^F2 * … * Pn^Fn

And the total number of divisors is: (F1 +1) * (F2 + 1) * … * (Fn + 1)

For example, 28 can be expressed as 2^2 * 7^1 so the total number of divisors is (2 + 1) * (1 + 1) = 6

Or, 36 = 2^2 * 3^2 so the total number of divisors is 3*3 = 9.

Coding this formula was pretty straightforward. Unfortunately, the resulting program ground to a halt once I started looking for more than 200 divisors – and this has had me stumped for a couple of days. I knew my reasoning was sound and I could see the program generating correct results for small numbers of divisors, but I could not figure out why it didn’t scale.

It wasn’t until I went back to look at the efficiency of my factorisation function that the following insight hit me: You don’t need to test whether a number is prime if you can guarantee that your loop will only look at prime mumbers.

This insight resulted in the following, much more efficient, function:

def Factorise(integer):
	factors=[]
	index = 2
	while integer > 1:
		if integer % index == 0:
			factors.append(index)
			integer=integer/index
		else:
			index += 1
	return factors

Starting with an index of 2 (the lowest prime) I simply divide the integer by the index until I get a non integer result. Then I increment the index and start again.

Because the function repeatedly divides out each factor, integer/index can only return an integer result if index is prime.

With this approach, I was able to solve the problem in about half a second.

flattr this!

While on holiday last month, my four-year-old son got hold of my camera and started taking photos. Lots of photos, some of which were quite good. Being the proud father that I am, I decided I wanted my desktop background to rotate through some of these photos.

This is very easy to achieve with Gnome 2 – and is implemented in the Cosmos transitioning wallpaper. So on the Monday, I copied a bunch of resized photos into a folder under /usr/share/backgrounds, copied the XML file that powers Cosmos into the same folder, tweaked it, and was rather pleased to find my desktop wallpaper smoothly transitioning from one photo to the next.

On Tuesday, I added a few more photos and amended the XML file accordingly. By Wednesday, I was bored of manually editing the XML and started thinking about how best to automate this.

I have finally found a bit of time to do something about this and am now ready to release version 0.1 of Macsen’s Transitioning Background.

It’s probably not the most elegant solution (there is a lot of copying and pasting going on in the build() function) and the resulting XML file is not pretty. But it works.

You can find a tarball and some instructions on the MTB Project Page or browse the source at GitHub.

flattr this!

In what I increasingly laughingly refer to as my spare time, I am taking another crack at improving my rather rudimentary Python skills. As a consequence of this, I have found myself browsing the Python PEPs.

PEP 20 – The Zen of Python captures the guiding principles for Python’s design into 20 aphorisms, only 19 of which have been written down. The 19 of which that have been written down are so true, and so true of any language, that I am repeating them here as a reminder to myself and anyone else that might pass this way.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

flattr this!