xrange not hashable - why not?

Sean Ross sross at connectmail.carleton.ca
Sun Jan 25 11:08:26 EST 2004


"Gerrit Holl" <gerrit at nl.linux.org> wrote in message
news:mailman.764.1075042048.12720.python-list at python.org...
> Hi,
>
> why is an xrange object not hashable?


I don't know the answer for this.


> I was trying to do something like:
>
> comments = {
>     xrange(0, 4): "Few",
>     xrange(4, 10): "Several",
>     xrange(10, 100): "A lot",
>     xrange(100, sys.maxint): "Can't count them"}
> for (k, v) in comments.items():
>     if n in k:
>         commentaar = v
>         break

There's a bit of an efficiency issue with using 'n in k' for something like
xrange(100, sys.maxint),
since you have to walk through the items in that range to see if n is in
there, and that's a large range.
Perhaps this would help:

class bounds:
    def __init__(self, start, stop, step=1):
        self.start = start
        self.stop = stop
        self.step = step
    def is_step(self, other):
            q, r = divmod(other-self.start, self.step)
            return r == 0
    def __contains__(self, other):
        return self.start <= other < self.stop and self.is_step(other)
    def __hash__(self):
        return id(self)
    def __repr__(self):
        return "bounds(start=%s, stop=%s, step=%s)"%\
               (self.start, self.stop, self.step)

import sys
import random

comments = {
    bounds(0, 4): "Few",
    bounds(4, 10): "Several",
    bounds(10, 100): "A lot",
    bounds(100, sys.maxint): "Can't count them"}

n = random.randint(0, sys.maxint)
print n

for k, v in comments.iteritems():
    print k
    if n in k:
        print v
        break
else:
    print n, "out of bounds"

HTH,
Sean





More information about the Python-list mailing list