472,958 Members | 2,623 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

Bitsets in Python

Hi,
does Python have any native support for bitsets? I dont seem to see
anything in the standard library?

Thanks,
Rajarshi

Jul 18 '05 #1
7 5931
> does Python have any native support for bitsets? I dont seem to see
anything in the standard library?


What do you mean 'bitsets'? Give a list of functionality of your
'bitsets', and it will be easy for us to tell you whether Python
includes it.

- Josiah
Jul 18 '05 #2
Josiah Carlson <jc******@nospam.uci.edu> wrote:
does Python have any native support for bitsets? I dont seem to see
anything in the standard library?


What do you mean 'bitsets'? Give a list of functionality of your
'bitsets', and it will be easy for us to tell you whether Python
includes it.


BitSets crop up in (at least) C++ and Java. They allow you operate on
a sequence of bits using a friendlier interface than hacking about
with ^,|,& et al on integers. The Java BitSet interface:

http://java.sun.com/j2se/1.4.1/docs/...il/BitSet.html

I can't find anything like it in the standard library (If I've
overlooked it, I'd be chuffed to find out I'm wrong!). The OP might
find the following Cookbook recipe useful, though:

http://aspn.activestate.com/ASPN/Coo.../Recipe/219300

(At least I think so, I can't access the site at the moment...)

Matt
Jul 18 '05 #3
On Thu, Feb 05, 2004 at 05:50:57AM -0800, Matt wrote:
I can't find anything like it in the standard library (If I've
overlooked it, I'd be chuffed to find out I'm wrong!).


I also don't think there's anything in the standard library for it.
I vaguely recall talk that putting this in the 'array' module might be
the right thing to do:
array.array(array.BIT, '\xaa') array(array.BIT, [1, 0, 1, 0, 1, 0, 1, 0])

numarray also has arrays of bool, though I have to confess I'm not sure
how they're stored: numarray.zeros((16,), numarray.Bool)

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], type=Bool)

Jeff

Jul 18 '05 #4
BitSets crop up in (at least) C++ and Java. They allow you operate on
a sequence of bits using a friendlier interface than hacking about
with ^,|,& et al on integers. The Java BitSet interface:


I would suggest subclassing int:

class bitset(int):
def __getitem__(self, k):
return (2**k & self) >> k
def __setitem__(self, k, v):
#this doesn't work
if v:
return bitset(2**k | self)
elif self[k]:
return bitset(2**k ^ self)

Unfortunately, due to the semantics of item setting a[i] = j, you cannot
return anything from a setitem, and integers are immutable, so you
cannot modify bitset directly.

Sounds like something in need of a custom class. Thankfully it wouldn't
be too difficult.

- Josiah
Jul 18 '05 #5
ma*********@yahoo.co.uk (Matt) wrote in message news:<94**************************@posting.google. com>...
Josiah Carlson <jc******@nospam.uci.edu> wrote:
does Python have any native support for bitsets? I dont seem to see
anything in the standard library?


What do you mean 'bitsets'? Give a list of functionality of your
'bitsets', and it will be easy for us to tell you whether Python
includes it.


BitSets crop up in (at least) C++ and Java. They allow you operate on
a sequence of bits using a friendlier interface than hacking about
with ^,|,& et al on integers. The Java BitSet interface:

http://java.sun.com/j2se/1.4.1/docs/...il/BitSet.html

I can't find anything like it in the standard library (If I've
overlooked it, I'd be chuffed to find out I'm wrong!). The OP might
find the following Cookbook recipe useful, though:


Depending on your needs, you might find Sam Rushing's npstruct module
to be of use.

npstruct: An extension module useful for parsing and unparsing binary
data structures. Somewhat like the standard struct module, but with a
few extra features (bitfields, user-function-fields, byte order
specification, etc...) and a different API more convenient for
streamed and context-sensitive formats like network protocol packets,
image and sound files, etc...

http://nightmare.com/software.html

-- Graham
Jul 18 '05 #6
Jeff Epler <je****@unpythonic.net> wrote:
I also don't think there's anything in the standard library for it.
I vaguely recall talk that putting this in the 'array' module might be
the right thing to do:
>>> array.array(array.BIT, '\xaa')

array(array.BIT, [1, 0, 1, 0, 1, 0, 1, 0])


Alternatively there could be support for "generating all tuples" a la
Knuth. The code below could be used for conversions to and from
binary, but it would be also be useful for datetime computations,
lexical permutations and other things. Doing it this way would solve
various requests simultaneously.

For datetime one could use [24,60,60] as bases, for binary with 3 bits
one could use [2,2,2], for permutations of a list of length 5 one
could use [5,4,3,2] as bases (although after using this as a starting
point I found some shorter lexical ranking and unranking functions).

Anton

def rank(L,bases):
res,multiplier = 0,1
for x,b in zip(L[::-1],bases[::-1]):
res += x*multiplier
multiplier *= b
return res

def unrank(d,bases):
res = []
for b in bases[::-1]:
d,m = divmod(d,b)
res.append(m)
return res[::-1]

def test():
bases = [2,2,2]
n = reduce(lambda x,y: x*y,bases)
for i in range(n):
x = unrank(i,bases)
print i,x
assert i == rank(x,bases)

if __name__=='__main__':
test()

output:

0 [0, 0, 0]
1 [0, 0, 1]
2 [0, 1, 0]
3 [0, 1, 1]
4 [1, 0, 0]
5 [1, 0, 1]
6 [1, 1, 0]
7 [1, 1, 1]


Jul 18 '05 #7
On Tue, 03 Feb 2004 19:56:36 -0800, Josiah Carlson wrote:
does Python have any native support for bitsets? I dont seem to see
anything in the standard library?


What do you mean 'bitsets'? Give a list of functionality of your
'bitsets', and it will be easy for us to tell you whether Python
includes it.


Sorry for th late reply. Thanks to everybody who responded.

A little background to the problem - I'm evaluating molecular fingerprints
which use bitsets of length N and set certain bits on depending on whether
a feature is present. So I was essentially looking for Java style bitsets.

In the end I wrote a small class which did the job (since all I need is to
keep track of which positions are on)

Thanks,

--
-------------------------------------------------------------------
Rajarshi Guha <ra******@presidency.com> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
-------------------------------------------------------------------
Q: What's purple and commutes?
A: An abelian grape.

Jul 18 '05 #8

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

Similar topics

1
by: Emile van Sebille | last post by:
QOTW: "If we get 2.3.3c1 out in early December, we could release 2.3.3 final before the end of the year, and start 2004 with a 100% bug-free codebase <wink>." -- Tim Peters "cjOr proWe vbCould...
0
by: Emile van Sebille | last post by:
QOTW: "Have you ever used the copy module? I am *not* a beginner, and have used it *once* (and I can't remember what for, either)." -- Michael Hudson "It will likely take a little practice...
2
by: Allen | last post by:
I'm using Python to do some simple network programming, and found the struct module very useful for such things, but is there a way to easily manipulate bitsets such as a 16 bit word being split...
1
by: Sean Farrow | last post by:
Hi: Will the defaul vector < operator allow me to compare two vectors of std:: bitsets? If not how do I get round this? Cheers Sean.
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.