[Chicago] Cartesian 1111 to 4444.....to nnnn (general case)

Robare, Phillip (Randstant) proba at allstate.com
Fri Jul 17 23:59:54 CEST 2015


>>  If there's a harder way to solve a problem, that's the way he wants me to do it.

In that case, revise your code again.  What you have is getting better but can be still more general and easy to modify.

Each of columns of your output can represented as elements of a new class.  Let's call the class a Column since it will end up being written out as a column in the output.  This class has the list of values being iterated over, a current value, and an instance of the Column class that is to the right (None on the rightmost column).  This class has a generator that increments the current value, checks to see if it has gone off the end, and if not yields.  If it has gone past the end it sets the current value to the first position and calls the next() method of the generator in the class to the right (if the reference is not None).  There are some other nuances to the generator but I want you to discover them instead of having them laid out for you.

Now your vector in the class CartesianProductN becomes a vector of four of these classes (or N of them) and addOne() just calls the next() method of the lowest order Column generator.  print() becomes querying the current value of each column class in the vector.

Now you can generalize not just the number of columns in the vector but also the number and type of elements that are being iterated over.

Also, if you are going to write in Python, start writing unit tests.  Look at the unittest module in the python documentation.  Thinking about how to write code so that it is testable is a good way to guide yourself to writing code that is well structured as well.

I would also encourage you to pursue learning OCaml.  It will help your thinking about programming to learn a language that is so strict about types that it can compile to very fast code.  (It will also make you appreciate Python.)  Here is a good blog post about how to go about learning it: http://blog.nullspace.io/beginners-guide-to-ocaml-beginners-guides.html

One of the learning resources for OCaml is the 99 problems page http://ocaml.org/learn/tutorials/99problems.html.  I would encourage you to also try these problems in Python also to get a feel for how you can express the same algorithm in different languages.

Phil Robare

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20150717/36eff7f9/attachment.html>


More information about the Chicago mailing list