Lisp mentality vs. Python mentality
Arnaud Delobelle
arnodel at googlemail.com
Sun Apr 26 09:08:49 EDT 2009
bearophileHUGS at lycos.com writes:
> You can also use quite less code, but this is less efficient:
>
> def equal_items(iter1, iter2, key=lambda x: x):
> class Guard(object): pass
> try:
> for x, y in izip_longest(iter1, iter2, fillvalue=Guard()):
> if key(x) != key(y):
> return False
> except TypeError: # intercepts key(guard)
> return False
> return True
You don't want to silence TypeErrors that may arise from with key() when
x or y is not a Guard, as it could hide bugs in key(). So I would write
something like this:
def equal_items(iter1, iter2, key=lambda x: x, _fill = object()):
for x, y in izip_longest(iter1, iter2, fillvalue=_fill):
if x is _fill or y is _fill or key(x) != key(y):
return False
return True
(untested)
Another way would be:
def equal_items(iter1, iter2, key=lambda x: x):
iter1, iter2 = iter(iter1), iter(iter2)
for x, y in izip(iter1, iter2):
if key(x) != key(y):
return False
for x, y in izip_longest(iter1, iter2):
return False
return True
(untested)
--
Arnaud
More information about the Python-list
mailing list