Archive

Posts Tagged ‘gotcha’

Inadvertent psychometric testing with Python

At some point – such as during the course of a job interview –  you’ve may have taken a numerical reasoning test with questions such as this:

Q. What is the next number in the sequence 81, 87, 84, 90, 87, ?

See the end of article for the answer.

Now, another one, this time in your Python interpreter.

>>> s = 'python'
>>> s[:-5]
'p'
>>> s[:-4]
'py'
>>> s[:-3]
'pyt'
>>> s[:-2]
'pyth'
>>> s[:-1]
'pytho'

and the next is the series is…

>>> s[:-0]
''

Huh!?

The surprise happens because of course the zeroth character is at the beginning of the string, rather than one beyond the end. It took me quite a while today to locate a bug caused by this negative indexing combined with slicing effect, subtly concealed as s[:-x] because intuitively we think that the identity:

s[:len(s) - x] == s[:-x]

is true for all x, when in fact it’s only true for 0 < x <= len(s). If Python was always based on one's complement binary representations I'd suggest that we use negative zero to represent the virtual character one beyond the end of the string and positive zero to represent the character at the beginning. I suspect however that my PEP would be short-lived. And rightfully so!

˙Ɛ6 sı ɹǝʍsuɐ ǝɥ⊥

Categories: Python Tags: ,