# Solving a math puzzle with Python’s generator expressions

Recently James Grime of numberphile-fame posted a puzzle on YouTube. The video is right here but the question is (if you don’t care to watch): “How many ways are there to completely fill a Noughts and Crosses (tic-tac-toe) board, with four noughts and five crosses? Not including rotations and reflections.”

So I am not much of a mathematician and I also did not really care for fopping about much so I wrote a small program in python to find the solution. And I took the chance to make a post about generator expressions in python as well.

A generator expression can take two general forms:

def gen(count):
c = 10
while c > 0:
yield c
c = c - 1

Here the yield keyword is what it’s all about. This will generate an iterable object that returns the yielded items. The cool thing is, that computation of this method is suspended until the next item is needed.

If you already have an iterable you can create a new generator expression from it:

g = (x for x in gen(10))

Here you can filter or map the value of x as you will see. And again, this is only a generator. No computation happens unless you actually want to print any values or you manifest them into a list.

you will find the source code of my solution below the fold

# Constructors in Python: overwriting __new__ and the singleton pattern

About all object-oriented languages allow you to overwrite the constructor of a particular self-defined type. In Java (and C#) this looks somewhat like that:

public class A(object) {
constructor A() {
// Do Something
}
}

If you think the parameters somehow merit the abortion of the object creation, you can only throw an exception. You only can do that. An object of (in this case) type A is always returned. You can’t even return a different object or an object of a subclass of A. This convention led to the factory pattern in which a static method is called to decide which specific constructor of which specific class to run. Since the method is declared as returning the supertype, it can return any subptype as well. But the factory-pattern can sometimes get out of hand.

If you get started with python you commonly see __init__(self [, args]) as the method you need to overwrite in order to get a constructor.

class A(object):
def __init__(self):
pass

And it is true that this is exactly what is written above.
Note: in python, methods are objects (and could be swapped any time). Therefore the own instance cannot be bound outside the method scope and it is always passed by the calling instance as the first parameter. Therefore any non-static method of a class starts with “self” (or “s” or whatever you want to call it) as its first parameter.

So __init__ is, as is the constructor in C# or Java, only called when the instance has already been created. So why is it called a constructor then? Historical reasons, for one. But with statically typed languages you can overload the constructor and build your instance from different parameters. A dynamically typed language like python has no method overloading. It is still good for initializing properties of the particular instance.

But there is another cool method in python which you can overwrite: __new__(C [,args]) in which the class to create an instance of is passed in C and the rest of the arguments in args. And now you can build something like this:

class A(object):
pass

class B(object):
def __new__(C):
return A()

In statically typed languages it is almost always true that A() returns an object of type A. But in python, this does not need to be true. You can put your factory right there as the constructor of the superclass and it looks really neat.

# Ich löse mein Mathe-Abitur mit Sage/SciPy – Teil 1: Analysis

Ich habe mein Mathe-Abitur erfolgreich bestanden und nun studiere ich Medien-Informatik. Das erste Mal, seit ich sie geschrieben habe, schaue ich mir die Prüfungsaufgaben an. Ich versuche hier die Aufgaben mit Hilfe von Sage zu lösen. Dies ist zum Einen eine Auffrischung, ob ich noch weiß, was ich aus mathematischer Sicht mache aber auch eine Übung bzw. ein Beispiel, wie man mit Sage seine Mathe-Aufgaben lösen kann.
In Code-Tags eingefasste Statements sind Sage-Code. Das Worksheet ist unten zum Download angehängt.

# Die Grund-Aufgabe

Gegeben ist folgende Funktion: $y=f_t(x)=e^{tx}(x-1)^2 ~~~~~ (x \in R) ~~~~~ (t \in R, t > 0)$

Außerdem ist diese Funktion, für alle weiteren Aufgaben, im Intervall von -10 bis 2 gezeichnet (beides einschließlich). Das sieht so aus:
Weiterlesen

# Python pregenerates class properties

This article is a reference because this cost me about an hour to debug:

class test(object): foo = []

 

a = test() b = test() a.foo.append("bar") print b.foo #['bar']

When you define the class (test, in this case), any class properties will be instanciated on class-definition and not on object instanciation. Therefore, when you create multiple copies of a class, they will have the same actual object as class properties. You should instanciate those attributes in the init-method.

For this reason, the following code will generate output, even though it looks like it probably shouldn’t, because not a single object was created:
def f(): print "foo"

 

class test(object): foo = [f()]

This will obviously not concern you, if you are – as you should – using immutable objects.

# Syntactical sugar in Python: map, filter, reduce vs. the python way

This article is going to try to shed some light on how to convert map, reduce and filter (often used with lambda expressions) in python into a syntax conforming to “the python way”. At the bottom you will find a download link to execute this stuff for yourself.

l = range(10) print l #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This is going to be the list (l) we’re working on.

What we’ll be looking at first, is iterating through this list and applying a function. And what simpler function could there be, than the identity?
a = map(lambda x: x, l) b = list(x for x in l) print a, b #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If you don’t really know what the we did in (a) you may want to read up on lambda expressions, a topic I am not covering now. We need the list-method in (b) because map() always returns a list and the for-expression coughs up a generator object which we have to fully evaluate and convert to a list, to get the equivalent. Generator objects I will cover in the future. For now, suffice to say, it has a reason we are applying the list-function.