Przejdź do głównej zawartości

Posty

Wyświetlanie postów z maj, 2013

Bugs on a board - modern concurrency in Clojure

[ Inspired by Rick Hickey's Ant Colony Simulation ] Having said before that Clojure is great, I feel obliged to provide a concrete example of a concurrent Clojure program. We will implement a simulation of N bugs walking randomly on an X x Y board. If two bugs walk onto the same cell, they both vanish. Let's start!

The board has dimensions specified as follows:

(def dimx 50)
(def dimy 50)

A bug performs one step from the current cell by randomly altering its (x,y) coordinates. Each coordinate is incremented or decremented by 1, or it stays the same.

(defn random-step [n]
  (let [step (rand-int 3)]
    (cond (= step 2) (dec n)
      (= step 1) (inc n)
      (= step 0) n)))

Next location for a bug will be randomly generated, unless a bug is at a border. In that case, it immediately jumps in the opposite direction.

(defn next-loc [loc]
(let [x (loc 0) y (loc 1)
      newx (cond (= x (dec dimx)) (dec x)
                 (= x 0) (inc x)
                 :else (random-step x))
    …

Code Kata: shopping list search

We have a list of, let's say, goods we bought at a shop (or you can imagine any other list that you like):

|        Name        |      Quantity      |       Price      |
|        Beer          |           10          |        30            |
|       Pickles        |           1           |        12            |
|     Red beans    |            2           |        22            |
...

The task is to write a piece of code that will search through the list and will display each row that matches search criteria. Too simple? Maybe. But consider these additional hints:
search criteria may not be exact. The string "bean" might match "Red beans"we may even be searching for any of a few items: rows one and three will both match if our search criteria are "any of 'beer', 'bean' ". I recommend that you start this kata with an exact search for one item and then gradually move towards the "like/contains" criteria and to "any of" c…

Do I really have to call super(...).__init__ in Python?

Yes. But, if you prefer a longer answer:

Class B inherits from class A. When implementing B's __init__ function, we may call A's init by writing:

super(B, self).__init__(arguments of A's __init__)

Is it really necessary? After all, in C++ or Java the constructor of base class is called automatically, so shouldn't it be called automatically in Python as well?

The point is that __init__ is not a constructor. Python objects are constructed with __new__. __init__ is used to initialize an object with concrete values, either defaults or passed as __init__'s parameters.

Need more details? Read Python docs at http://docs.python.org/2/reference/datamodel.html#object.__new__