Python less error-prone than Java
Christoph Zwerschke
cito at online.de
Sat Jun 3 17:23:32 EDT 2006
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