R
Raymond Hettinger
[Tim Roberts]
[Uwe Schmitt]
In the vague category of Most Pythonic, code using "filter", "lambda",
and "and" tend to be losers. Straight-forward loops run reasonably
fast and are much more clear:
def ishexstring(s):
for c in s:
if c not in '0123456789abcdefABCDEF':
return False
return True
The category of Fastest Code is much less vague but tends towards
using fancy tricks:
def ishexstring(s):
try:
int(s, 16)
except ValueError:
return False
return True
The category of Cutest Code tends to make creative use of data
structures:
def ishexstring(s):
return not sets.Set(s).difference('0123456789abcdefABCDEF')
Raymond Hettinger
Well, more Pythonish yet is to avoid the extraneous local variables,
avoid the use of a type as a parameter name, and use as many
little-used builtins as possible:
def ishexdigit(char):
return char in string.hexdigits
def ishexstring(strng):
return filter(ishexdigit, strng) == strng
[Uwe Schmitt]
better/faster/more pythonic:
return reduce(lambda a,b: a and ishexdigit(b), strng, True)
In the vague category of Most Pythonic, code using "filter", "lambda",
and "and" tend to be losers. Straight-forward loops run reasonably
fast and are much more clear:
def ishexstring(s):
for c in s:
if c not in '0123456789abcdefABCDEF':
return False
return True
The category of Fastest Code is much less vague but tends towards
using fancy tricks:
def ishexstring(s):
try:
int(s, 16)
except ValueError:
return False
return True
The category of Cutest Code tends to make creative use of data
structures:
def ishexstring(s):
return not sets.Set(s).difference('0123456789abcdefABCDEF')
Raymond Hettinger