[Tutor] another better way to do this ?
eryksun
eryksun at gmail.com
Mon Jan 13 20:34:34 CET 2014
On Mon, Jan 13, 2014 at 1:36 PM, Keith Winston <keithwins at gmail.com> wrote:
> Yikes, Peter, that's scary. Wow.
Yikes, watch the top posting. :)
>> In the mean time here is my candidate:
>>
>> def test(a, b):
>> a = iter(a)
>> return all(c in a for c in b)
Refer to the language reference discussion of comparison expressions:
http://docs.python.org/3/reference/expressions.html#not-in
For user-defined classes which do not define __contains__() but
do define __iter__(), x in y is true if some value z with
x == z is produced while iterating over y.
Since the iterator returned by `iter(a)` doesn't implement
__contains__, the interpreter iterates it looking for a match for `c`.
In effect, Peter smuggled a state variable into the expression,
equivalent to `index` in your code.
CPython Implementation
The "in" comparison operator is implemented abstractly by
PySequence_Contains. If the type doesn't define sq_contains, then the
call is routed to _PySequence_IterSearch, which calls PyIter_Next
until it either finds a match or the iterator is exhausted.
More information about the Tutor
mailing list