Wrote a python script to find the partitions of an integer (a list of
all the ways you can express n as a sum of integers). For example, the
partitions of 5 are
5
4+1
3+2
2+2+1
3+1+1
2+1+1+1
1+1+1+1+1
My method, however, generates plenty of duplicates (note the if
statement to catch them). Generating the 15 partitions of 7, for
example, also generates 19 duplicates. Can someone spot a way to improve
or eliminate the duplicates?
Nick.
def partitions(n):
"""Create a list of all of n's partitions"""
allpartitions = []
onepartition = [n]
allpartitions.a ppend(onepartit ion)
# p steps through allpartitions, looking for those which are not all 1s
p = 0
while p != len(allpartitio ns):
onepartition = allpartitions[p]
# check each element of this partition
i = 0
while i != len(onepartitio n):
# if there is a non-1, then create a new partition
if onepartition[i] > 1:
hi = onepartition[i] - 1
lo = 1
while hi >= lo:
newpartition = onepartition[:i] + [hi] + [lo] +
onepartition[i+1:]
newpartition.so rt()
newpartition.re verse()
# newpartition may be a copy of an existing one!!!
if not newpartition in allpartitions:
allpartitions.a ppend(newpartit ion)
hi -= 1
lo += 1
i += 1
p += 1
print dups
return allpartitions
print partitions(7) 5 4311
Am Samstag, 24. Juli 2004 18:08 schrieb Nick J Chackowsky: My method, however, generates plenty of duplicates (note the if statement to catch them). Generating the 15 partitions of 7, for example, also generates 19 duplicates. Can someone spot a way to improve or eliminate the duplicates?
def _yieldParts(num ,lt):
if not num:
yield []
for i in range(min(num,l t),0,-1):
for parts in yieldParts(num-i,i):
yield [i]+parts
def yieldParts(num) :
for part in _yieldParts(num ,num):
yield part
parts = list(yieldParts (7,7))
print len(parts)
print parts
will only yield non-duplicate partitions, and functions as a generator, so you
don't need to store all partitions in memory. It's not iterative as your
example, but you could implement caching so that its runtime decreases to
iterative.
Heiko.
Nick J Chackowsky wrote: Wrote a python script to find the partitions of an integer (a list of all the ways you can express n as a sum of integers). For example, the partitions of 5 are 5 4+1 3+2 2+2+1 3+1+1 2+1+1+1 1+1+1+1+1
My method, however, generates plenty of duplicates (note the if statement to catch them). Generating the 15 partitions of 7, for example, also generates 19 duplicates. Can someone spot a way to improve or eliminate the duplicates?
Nick.
You should check this recipe:
Generator for integer partitions http://aspn.activestate.com/ASPN/Coo.../Recipe/218332
This is a cool example of how to use generators with recursion.
--
George
Am Samstag, 24. Juli 2004 18:25 schrieb Heiko Wundram: [snip]
Ahh, slight error crept in:
def _yieldParts(num ,lt): if not num: yield [] for i in range(min(num,l t),0,-1):
- for parts in yieldParts(num-i,i):
+ for parts in _yieldParts(num-i,i): yield [i]+parts
def yieldParts(num) : for part in _yieldParts(num ,num): yield part
parts = list(yieldParts (7,7)) print len(parts) print parts
Heiko.
In article <pN************ **@animal.nntps erver.com>,
Nick J Chackowsky <me************ *@hotmail.com> wrote: Wrote a python script to find the partitions of an integer (a list of all the ways you can express n as a sum of integers). For example, the partitions of 5 are 5 4+1 3+2 2+2+1 3+1+1 2+1+1+1 1+1+1+1+1
My method, however, generates plenty of duplicates (note the if statement to catch them). Generating the 15 partitions of 7, for example, also generates 19 duplicates. Can someone spot a way to improve or eliminate the duplicates?
Nick.
I propose the following recursive solution:
def sorted(tpl):
copy = list(tpl)[:] ; copy.sort()
return tuple(copy)
def nat_partitions( n, mem = {}):
assert n > 0
if mem.has_key(n):
return mem[n]
parts = {}
for b in range(1, n):
for p in nat_partitions( n - b):
parts[sorted(p + (b,))] = True
mem[n] = parts.keys() + [(n,)]
return mem[n] from pprint import pprint pprint(nat_part itions(7))
[(1, 1, 1, 1, 3),
(1, 1, 2, 3),
(3, 4),
(1, 3, 3),
(1, 2, 4),
(1, 1, 1, 2, 2),
(1, 1, 1, 1, 1, 2),
(1, 1, 1, 1, 1, 1, 1),
(1, 1, 1, 4),
(1, 1, 5),
(2, 2, 3),
(2, 5),
(1, 2, 2, 2),
(1, 6),
(7,)]
Certainly the algorithm is simple enough, though there is a certain
amount of thrashing between lists and tuples doing it this way. But,
with the memoization, it performs reasonably well.
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA
* Nick J Chackowsky <me************ *@hotmail.com> in comp.lang.pytho n: Wrote a python script to find the partitions of an integer (a list of all the ways you can express n as a sum of integers). For example, the partitions of 5 are 5 4+1 3+2 2+2+1 3+1+1 2+1+1+1 1+1+1+1+1
There have been good answers to your questions in the thread, so I won't
give more Python code here. I just wanted to point out this draft from
Knuth where many details about the theory of partitions and the related
algorithms can be found. I guess this will be of interest for all
contributors of the thread if they do not know this document already.
<http://www-cs-faculty.Stanfor d.EDU/~knuth/fasc3b.ps.gz>
--
DW This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Steve |
last post by:
This post has two parts. First is my feedback on sets. (Hello? Last
summer called, they want their discussion thread back...) Second is some
questions about my implementation of a partition function for sets.
Part 1.
---
>From: Raymond Hettinger (vze4rx4y@verizon.net)
>Subject: Py2.3: Feedback on Sets
>Newsgroups: comp.lang.python
>Date: 2003-08-11 23:02:18 PST
|
by: RunLevelZero |
last post by:
I need a way to detect hard drives and their partitions... labels would
be nice too... I did some googling but did not find anything all too
useful. This will strictly be on Linux / Unix so any help would be
greatly appreciated.
TIA
|
by: cantabile |
last post by:
Hi, I'd like to get drives and partitions (and their size too) with
python under Linux. So far, I thought of reading /proc/partitions but
maybe i could use fdsik also ?
How would I do that in python ?
Thanks for your help (newbie here :) )
|
by: sandeep G |
last post by:
I've a table which has a number & a blob column, both of which are NOT
NULL type. This table is composite partitioned using range & hash on
the same column.
Each partition is sub partitioned into two.
Now if I try to move the partitions to a different tablespace I get an
oracle error sayiing that ERROR: ORA_14257 cannot move partition other
than a Range or Hash partition
Now is there any other way to move the partition to another
|
by: Jack Li |
last post by:
Hi All,
I have DB2 EEE 7.2 12 db partitions running on AIX 5.1ML5 P690( one
server). The AIX workload manager is on. I started the same peoplesoft
job on all 12 nodes at the same time. But some node(partition)
processing speed are much faster than the others. The fastest node
took 15 hours. But the slowest node took 17 hours.
According to DBA, the data are evenly disributed on 12 partitions. The
configuration of the partitions are...
| |
by: jcgeorge |
last post by:
I have a Windows DPF (v8.2.2) environment.
2 Nodes
5 Partitions
Server1 - Cat (0) Data (1) Data (2)
Server2 - Data (3) Data (4)
I want to use block-based IO, but I do not want the same size block
area of the bufferpool in each partition, I want a smaller value in the
catalog partition - because the bufferpool size is much smaller.
|
by: Claude Henchoz |
last post by:
Hi
Is there any way of listing partitions on a (win32) computer without
using WMI?
Cheers, Claude
|
by: arunrocks |
last post by:
Hi
I am having a requirement to create a db in 2 out of 8 partitiones.
I have the following doubts.
1. should I create a new instance in 2 partitions alone (the present
instance spans 8 nodes)
2. or is there a way to create the db in 2 out of 8.
If I have to create a new instance, (its a BCU from IBM)
I;d be happy if someone would link a material (1st time I am working
in a partitioned env)
Should I execute db2icrt in each of the...
|
by: Nepomuk |
last post by:
In most modern distributions of Linux and Unix (at least ones with graphical environments like KDE, Gnome or XFCE), you get to mount your partitions easily from the desktop. In some cases however, it isn't that easy.
Note, that all of these commands have to be run in a terminal as root user. To open a terminal (sometimes called a console), either press ALT+F2 and type xterm (alternatives could be konsole or terminal) or press CRTL+ALT+F1 to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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: 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...
|
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: 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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |