I'm looking for a good Python way to generate (enumerate) the 2**N
tuples representing all vertices of the unit hypercube in N-dimensional
hyperspace.
For example, for N=4 the Python code should generate the following 2**N
= 16 tuples:
(1,1,1,1), (1,1,1,-1),
(1,1,-1, 1), (1,1,-1,-1),
(1,-1,1,1), (1,-1,1,-1),
(1,-1,-1, 1), (1,-1,-1,-1),
(-1,1,1,1), (-1,1,1,-1),
(-1,1,-1, 1), (-1,1,-1,-1),
(-1,-1,1,1), (-1,-1,1,-1),
(-1,-1,-1, 1), (-1,-1,-1,-1)
Maybe converting each integer in the range(2**N) to binary, then
converting to bit string, then applying the "tuple" function to each
bit string?
Thanks for your help. 9 2480
"Dr. Colombes" <Dr********@yah oo.com> writes: I'm looking for a good Python way to generate (enumerate) the 2**N tuples representing all vertices of the unit hypercube in N-dimensional hyperspace. For example, for N=4 the Python code should generate the following 2**N = 16 tuples:
Here's a recursive generator:
def hypercube(ndims ):
if ndims == 0:
yield ()
return
for h in 1, -1:
for y in hypercube(ndims-1):
return (h,)+y print list(hypercube( 4))
[(1, 1, 1, 1), (1, 1, 1, -1), (1, 1, -1, 1), (1, 1, -1, -1), (1, -1,
1, 1), (1, -1, 1, -1), (1, -1, -1, 1), (1, -1, -1, -1), (-1, 1, 1, 1),
(-1, 1, 1, -1), (-1, 1, -1, 1), (-1, 1, -1, -1), (-1, -1, 1, 1), (-1,
-1, 1, -1), (-1, -1, -1, 1), (-1, -1, -1, -1)]
Maybe converting each integer in the range(2**N) to binary, then converting to bit string, then applying the "tuple" function to each bit string?
Yeah you could do that too.
Dr. Colombes wrote: Maybe converting each integer in the range(2**N) to binary, then converting to bit string, then applying the "tuple" function to each bit string?
A direct translation of that:
def perm(n):
rv = []
for i in xrange(2L**n):
cur = []
for j in range(n):
cur.append(1-2*(bool(i & (1<<j))))
# cur is in reversed order LSB first, but as you seemingly don't
# care about order of the returned tuples, this is irrelevant.
rv.append(tuple (cur))
return rv
modelnine@phoen ix ~ $ python
Python 2.4.2 (#1, Dec 22 2005, 17:27:39)
[GCC 4.0.2 (Gentoo 4.0.2-r2, pie-8.7.8)] on linux2
Type "help", "copyright" , "credits" or "license" for more information. from test1 import perm perm(5)
[(1, 1, 1, 1, 1), (-1, 1, 1, 1, 1), (1, -1, 1, 1, 1), (-1, -1, 1, 1, 1), (1,
1, -1, 1, 1), (-1, 1, -1, 1, 1), (1, -1, -1, 1, 1), (-1, -1, -1, 1, 1), (1,
1, 1, -1, 1), (-1, 1, 1, -1, 1), (1, -1, 1, -1, 1), (-1, -1, 1, -1, 1), (1,
1, -1, -1, 1), (-1, 1, -1, -1, 1), (1, -1, -1, -1, 1), (-1, -1, -1, -1, 1),
(1, 1, 1, 1, -1), (-1, 1, 1, 1, -1), (1, -1, 1, 1, -1), (-1, -1, 1, 1, -1),
(1, 1, -1, 1, -1), (-1, 1, -1, 1, -1), (1, -1, -1, 1, -1), (-1, -1, -1, 1,
-1), (1, 1, 1, -1, -1), (-1, 1, 1, -1, -1), (1, -1, 1, -1, -1), (-1, -1, 1,
-1, -1), (1, 1, -1, -1, -1), (-1, 1, -1, -1, -1), (1, -1, -1, -1, -1), (-1,
-1, -1, -1, -1)]
modelnine@phoen ix ~ $
--- Heiko.
Heiko Wundram <mo*******@bi t-bukket.org> writes: def perm(n): rv = [] for i in xrange(2L**n): cur = [] for j in range(n): cur.append(1-2*(bool(i & (1<<j)))) # cur is in reversed order LSB first, but as you seemingly don't # care about order of the returned tuples, this is irrelevant. rv.append(tuple (cur)) return rv
def perm(n):
return [tuple([(1,-1)[(t>>i)%2] for i in xrange(n)])
for t in xrange(2L**n)] perm(4)
[(1, 1, 1, 1), (-1, 1, 1, 1), (1, -1, 1, 1), (-1, -1, 1, 1), (1, 1,
-1, 1), (-1, 1, -1, 1), (1, -1, -1, 1), (-1, -1, -1, 1), (1, 1, 1,
-1), (-1, 1, 1, -1), (1, -1, 1, -1), (-1, -1, 1, -1), (1, 1, -1, -1),
(-1, 1, -1, -1), (1, -1, -1, -1), (-1, -1, -1, -1)]
Paul Rubin wrote: def perm(n): return [tuple([(1,-1)[(t>>i)%2] for i in xrange(n)]) for t in xrange(2L**n)]
or replace that with:
def perm(n):
return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n)))
for t in xrange(2L**n))
to get a generator like in Paul's first example. Only works with Python 2.4+
though.
--- Heiko.
Heiko Wundram wrote: Paul Rubin wrote:
def perm(n): return [tuple([(1,-1)[(t>>i)%2] for i in xrange(n)]) for t in xrange(2L**n)]
or replace that with:
def perm(n): return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n))) for t in xrange(2L**n))
to get a generator like in Paul's first example. Only works with Python 2.4+ though.
--- Heiko.
Isn't this kind of coding beeing the result of suffering from the
post-pyContest illness syndrom?
Or is there another reason behind writing it that way sacrificing
readability like usage of less CPU time to run the code?
Or am I alone having trouble to read this kind of code because not
experienced enough in writing Python scripts?
Claudio
Dr. Colombes wrote: I'm looking for a good Python way to generate (enumerate) the 2**N tuples representing all vertices of the unit hypercube in N-dimensional hyperspace.
For example, for N=4 the Python code should generate the following 2**N = 16 tuples:
(1,1,1,1), (1,1,1,-1), (1,1,-1, 1), (1,1,-1,-1), (1,-1,1,1), (1,-1,1,-1), (1,-1,-1, 1), (1,-1,-1,-1), (-1,1,1,1), (-1,1,1,-1), (-1,1,-1, 1), (-1,1,-1,-1), (-1,-1,1,1), (-1,-1,1,-1), (-1,-1,-1, 1), (-1,-1,-1,-1)
Maybe converting each integer in the range(2**N) to binary, then converting to bit string, then applying the "tuple" function to each bit string?
Thanks for your help.
Is this just a special case for the list of list combine() function
posted not long ago ?
def combine_lol(seq ):
return reduce(lambda x,y: (a+(b,) for a in x for b in y), seq,
[()])
list(combine_lo l([(1,-1)]*4))
Claudio Grondi wrote: Heiko Wundram wrote: def perm(n): return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n))) for t in xrange(2L**n))
Isn't this kind of coding beeing the result of suffering from the post-pyContest illness syndrom?
I don't think what Paul Rubin posted is the sign of pyContest illness, as I
use two-level generator expressions such as this quite often in my code.
Why I didn't give this as the reponse to the OP was because it seems that
he's not that familiar with Python to be able to read this efficiently and
grap the concept behind the implementation immediately, that's why I
thought an explicit loop was in order.
But for any sufficiently advanced Python coder, I don't think this is
unreadable in the least.
--- Heiko.
Paul, Heiko:
Thank you for the quality, parsimony and promptness of your
excellent suggestions.
I wasn't familiar with the Python "yield" function.
Dr. Colombes
Heiko Wundram wrote: Claudio Grondi wrote:
Heiko Wundram wrote:
def perm(n): return (tuple(((1,-1)[(t>>i)%2] for i in xrange(n))) for t in xrange(2L**n))
Isn't this kind of coding beeing the result of suffering from the post-pyContest illness syndrom?
I don't think what Paul Rubin posted is the sign of pyContest illness, as I use two-level generator expressions such as this quite often in my code. Why I didn't give this as the reponse to the OP was because it seems that he's not that familiar with Python to be able to read this efficiently and grap the concept behind the implementation immediately, that's why I thought an explicit loop was in order.
But for any sufficiently advanced Python coder, I don't think this is unreadable in the least.
--- Heiko.
List comprehension is a nice thing when standalone.
I am usually able to read it from the left to the right and understand
directly.
But with nested list comprehensions I don't see directly what is going
on, because there are more than one identifier I don't know about at the
time of reading the expression and I am forced to read the entire
nestings with eventually some more code spread over it. The trouble is,
that there are no visual hints toward understanding of the used
algorithm like it is the case in the non-list-comprehension version and
I usually have to re-read the nested list comprehension from the right
to the the left in order to get the idea. I don't want to be forced to
read from the right to the left as I am used to read left-right,
top-down and I expect any text (also source code) to be that way.
Similar critics comes sometimes up when someone learns the German
language, because you are forced to read also a very, very long sentence
up to its end, before it is clear what is the action. I consider it as a
problem which would be nice to get rid of if possible, but it is much
easier to try to influence coding style than the usage of a language.
Can usage of deep (i.e. more than two levels) nested list comprehensions
be considered bad coding style?
Claudio This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jeff Wagner |
last post by:
I've spent most of the day playing around with lists and tuples to get a really good grasp on what
you can do with them. I am still left with a question and that is, when should you choose a list or
a tuple? I understand that a tuple is immutable and a list is mutable but there has to be more to it
than just that. Everything I tried with a list worked the same with a tuple. So, what's the
difference and why choose one over the other?
Jeff
|
by: vdavidster |
last post by:
Hello everyone,
I want to convert a tuple to a list, and I expected this behavior:
list(('abc','def')) ->
list(('abc')) ->
But Python gave me this behavior:
list(('abc','def')) ->
|
by: Popoxinhxan |
last post by:
HI guy
I am working on the web application that required to display
the chart image on the page. The process is clicking the button
and browser will popup another windows that displayed the
|
by: Bill Rust |
last post by:
I've created an "Add Item" wizard for VB.NET 2003 that allows a user to add a
specialized class that works with my application framework. In the wizard,
the user can select the interfaces they would like to support. During the
code generation phase, I add an "Implements Ixxx" for each interface they
select, but I've not yet figured out how to add the skeleton implementation
for those interfaces. Once the user opens the class in the VS...
|
by: taylorjonl |
last post by:
I am having a problem generating some soap proxies dynamically using
almost the exact same code as in the MSDN sample.
http://msdn2.microsoft.com/en-us/library/system.web.services.description.webreference(VS.80).aspx
It has very few differences, mainly I had to manipulate the document to
remove the Any tags that caused 400+ validation warnings but even after
getting the WebReference object ValidationWarnings to 0, it says...
| |
by: Will McGugan |
last post by:
Hi,
I'd like a generator that takes a sequence and yields tuples containing
n items of the sqeuence, but ignoring the 'odd' items. For example
take_group(range(9), 3) -(0,1,2) (3,4,5) (6,7,8)
This is what I came up with..
def take_group(gen, count):
|
by: George Sakkis |
last post by:
I've just started toying with the python bindings of BGL and I'm
puzzled from the following:
True
False
It seems that the vertices iterator creates new vertex objects every
time instead of iterating over the existing ones. This essentially
prevents, among other things, storing vertices as keys in a dictionary
since the hashes of the stored and the new vertex differ although they
|
by: C.L. |
last post by:
I was looking for a function or method that would return the index to the first
matching element in a list. Coming from a C++ STL background, I thought it might
be called "find". My first stop was the Sequence Types page of the Library
Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search
of the Library Reference's index seemed to confirm that the function did not
exist. A little later I realized it might be called...
|
by: Atran |
last post by:
Discover The 4D. The Impossible Hypercube:
http://www.metacafe.com/watch/624539/discover_the_4d_the_impossible_hypercube/
|
by: Debajit Adhikary |
last post by:
I'm writing this little Python program which will pull values from a
database and generate some XHTML.
I'm generating a <tablewhere I would like the alternate <tr>'s to be
<tr class="Even">
and
<tr class="Odd">
What is the best way to do this?
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |