Python less error-prone than Java

Simon Percivall percivall at gmail.com
Sat Jun 3 19:52:19 EDT 2006


Actually, you're wrong on all levels.

First: It's perfectly simple in Java to create a binary sort that sorts
all arrays that contain objects; so wrong there.

Secondly: The bug has nothing to do with static typing (I'm guessing
that's what you meant. Both Python and Java are strongly typed). The
problem is that ints are bounded in Java. They could easily have been
ints and then automatically coerced to (equivalent to) longs when they
got bigger; that they aren't is more a design fault than anything to do
with static typing. The equivalent in Python would have been if an
overflow exception was raised when the int got too big. It might have
been that way, typing or no typing.

Christoph Zwerschke wrote:
> You will often hear that for reasons of fault minimization, you should
> use a programming language with strict typing:
> http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html
>
> I just came across a funny example in which the opposite is the case.
>
> The following is a binary search algorithm in Java. It searches a value
> in an ordered array a of ints:
>
> public static int binarySearch(int[] a, int key) {
>      int low = 0;
>      int high = a.length - 1;
>      while (low <= high) {
>          int mid = (low + high) / 2;
>          int midVal = a[mid];
>          if (midVal < key)
>              low = mid + 1;
>          else if (midVal > key)
>              high = mid - 1;
>          else
>              return mid; // key found
>      }
>      return -(low + 1);  // key not found.
> }
>
> Now the same thing, directly converted to Python:
>
> def binarySearch(a, key):
>      low = 0
>      high = len(a) - 1
>      while low <= high:
>          mid = (low + high) / 2
>          midVal = a[mid]
>          if midVal < key:
>              low = mid + 1
>          elif midVal > key:
>              high = mid - 1;
>          else:
>              return mid # key found
>      return -(low + 1) # key not found.
>
> What's better about the Python version? First, it will operate on *any*
> sorted array, no matter which type the values have.
>
> But second, there is a hidden error in the Java version that the Python
> version does not have.
>
> See the following web page if you dont find it ;-)
> http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
> 
> -- Christoph




More information about the Python-list mailing list