473,667 Members | 2,568 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

xrange not hashable - why not?

Hi,

why is an xrange object not hashable?
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

Because:
- I found it easier to extend than:
if 0 <= n < 4: return "few"
elif ... # etc
- And better readable than:
if k[0] <= n < k[1]: # using tuples
- And much more memory efficient than tuple(...) (especially the
last one ;-)

It would not be difficult to let xrange have a hash:

hash((self.star t, self.step, self.stop))

would be sufficient, I think.

Hmm, start, step and stop appear to have disappeared in Python 2.3...
certainly makes it somewhat more difficult. I shouldn't even to containment
testing according to PEP 260, and Python 2.3.3 should warn me not to
do... it doesn't, however.

So, should I use one of the alternatives after all? Or does someone have
something better to offer?

yours,
Gerrit.

Jul 18 '05 #1
6 1347

"Gerrit Holl" <ge****@nl.linu x.org> wrote in message
news:ma******** *************** *************** @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__(se lf, other):
return self.start <= other < self.stop and self.is_step(ot her)
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.iterit ems():
print k
if n in k:
print v
break
else:
print n, "out of bounds"

HTH,
Sean
Jul 18 '05 #2

"Sean Ross" <sr***@connectm ail.carleton.ca > wrote in message
news:FS******** ********@news20 .bellglobal.com ...
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.


Hmm, I don't think what I said there is correct, please disregard.

Sorry for any confusion,
Sean
Jul 18 '05 #3
Sean Ross wrote:
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.

Hmm, I don't think what I said there is correct, please disregard.

I think you're right though:

90000000 in xrange(1,sys.ma xint) takes a long time to complete....

--Irmen
Jul 18 '05 #4
Gerrit Holl wrote:
why is an xrange object not hashable?


Because they don't have a notion of equality
beyond identity.

Regards,
Martin

Jul 18 '05 #5
Gerrit Holl wrote:
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
[...]
So, should I use one of the alternatives after all? Or does someone have
something better to offer?


I think you want bisect():

import bisect

ranges = [
(0, "Few"),
(4, "Several"),
(10, "A lot"),
(100, "Can't count them")
]

def makelookup(r):
bounds = [i[0] for i in r][1:]
names = [i[1] for i in r]
def find(value):
return names[bisect.bisect(b ounds, value)]
return find

lookup = makelookup(rang es)

# use it
last = ""
for i in range(-100, 1000):
if last != lookup(i):
last = lookup(i)
print i, last

Note that names needs one more entry than bounds. I "fixed" that by
discarding the first bounds item.

Peter
Jul 18 '05 #6
> why is an xrange object not hashable?
I was trying to do something like:
Could be a hold-over from xrange trying to have all of the features of a
list returned by range; lists are unhashable because they are mutable.
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 It would not be difficult to let xrange have a hash:

hash((self.star t, self.step, self.stop))
I don't believe anyone ever said it was. *wink*

Hmm, start, step and stop appear to have disappeared in Python 2.3...
I don't know about that:
Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright" , "credits" or "license" for more information.
help(xrange)

Help on class xrange in module __builtin__:

class xrange(object)
| xrange([start,] stop[, step]) -> xrange object

So, should I use one of the alternatives after all? Or does someone have
something better to offer?


Honestly it is one of those things that are easily remedied by a
custom-built class. Like the below:

class HashableXRange:
def __init__(self, s1, s2=None, s3=None):
if s2 is None:
s1, s2, s3 = 0, s1, 1
elif s3 is None:
s3 = 1
self.start = s1
self.stop = s2
self.step = s3
def __hash__(self):
return hash((self.star t, self.stop, self.step))
def __cmp__(self, other):
if isinstance(othe r, self.__class__) :
return cmp(self.start, other.start) or\
cmp(self.stop, other.stop) or\
-cmp(self.step, other.step)
return cmp(self.start, other)
def __iter__(self):
return iter(xrange(sel f.start, self.stop, self.step))
def __contains__(se lf, object):
if self.start <= object < self.stop:
if (object-self.start) % self.step == 0:
return 1
return 0

I included the __cmp__ function in order to give it a richer set of
behavior. One thing to note about hashes is that they are not required
to be unique. As such, the hashing algorithm is not the absolute best
algorithm ever. It is pretty good, but it is not guaranteed that
hash((a,b,c)) != hash((d,e,f)) for different sets of three objects.
Better to be safe than sorry.

I would have subclassed xrange, but Python 2.3 doesn't like that.
Apparently there is no subclassing for xranges.

- Josiah
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2577
by: Christian Neumann | last post by:
Hello, i have a problem with the built-in function xrange(). Could you by any chance be able to help? I use Python 2.3.4 (final) and i think there is a bug in the built-in
11
1645
by: Leif K-Brooks | last post by:
I was just playing around, and noticed that modules seem to be hashable. Can anyone explain that, especially given the fact that they're mutable? Python 2.3.3 (#1, May 7 2004, 10:31:40) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> hash(sys) -150589324 >>> sys.x = 42
29
2864
by: Steve R. Hastings | last post by:
When you compile the expression for i in range(1000): pass does Python make an iterator for range(), and then generate the values on the fly? Or does Python actually allocate the list and then step through it? I was under the impression that recent releases of Python optimize this
1
4078
by: Simon Pickles | last post by:
Hi, The term 'hashable'. Am I right in thinking it means it can be indexed? like a string or a dict? Thanks Si
1
8563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8646
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7390
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6203
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.