473,387 Members | 1,678 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Need some help to understand Python program..

Hi,,,

I am very interested about the following Python program, but I am
very beginner on Python.. I do not understand this algorithm,,

I would appreciated if you give me this algorithm to some other
popular programming language.
filename="Karp.py"


from __future__ import nested_scopes

import bisect

class _Num:
def __init__(self, value, index):
self.value = value
self.i = index

def __lt__(self, other):
return self.value < other.value

# This implements the Karmarkar-Karp heuristic for partitioning a set
# in two, i.e. into two disjoint subsets s.t. their sums are
# approximately equal. It produces only one result, in O(N*log N)
# time. A remarkable property is that it loves large sets: in
# general, the more numbers you feed it, the better it does.

class Partition:
def __init__(self, nums):
self.nums = nums
sorted = [_Num(nums[i], i) for i in range(len(nums))]
sorted.sort()
self.sorted = sorted

def run(self):
sorted = self.sorted[:]
N = len(sorted)
connections = [[] for i in range(N)]

while len(sorted) > 1:
bigger = sorted.pop()
smaller = sorted.pop()

# Force these into different sets, by "drawing a
# line" connecting them.
i, j = bigger.i, smaller.i
connections[i].append(j)
connections[j].append(i)

diff = bigger.value - smaller.value
assert diff >= 0
bisect.insort(sorted, _Num(diff, i))

# Now sorted contains only 1 element x, and x.value is
# the difference between the subsets' sums.

# Theorem: The connections matrix represents a spanning tree
# on the set of index nodes, and any tree can be 2-colored.
# 2-color this one (with "colors" 0 and 1).

index2color = [None] * N

def color(i, c):
if index2color[i] is not None:
assert index2color[i] == c
return
index2color[i] = c
for j in connections[i]:
color(j, 1-c)

color(0, 0)

# Partition the indices by their colors.
subsets = [[], []]
for i in range(N):
subsets[index2color[i]].append(i)

return subsets

N = 50
import math
x = [math.sqrt(i) for i in range(1, N+1)]
p = Partition(x)
s, t = p.run()
sum1 = 0L
sum2 = 0L
for i in s:
sum1 += x[i]
for i in t:
sum2 += x[i]
print "Set 1 sum", repr(sum1)
print "Set 2 sum", repr(sum2)
print "difference", repr(abs(sum1 - sum2))
Thanks for you help...


Jul 19 '05 #1
0 1120

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

Similar topics

10
by: Jeff Wagner | last post by:
I am in the process of learning Python (obsessively so). I've been through a few tutorials and read a Python book that was lent to me. I am now trying to put what I've learned to use by rewriting...
1
by: Alex Pavluck | last post by:
Hello. I am trying to teach myself PYTHON because I am interested in programming. I use SAS all day and I really like the way you can highlight code and submit just that section or submit the...
45
by: Joh | last post by:
hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = would like to produce : , , , ,
13
by: Heather Stovold | last post by:
Wow - deciding to program in python sure requires a lot of decisions! So far: I've decided on python for the programming language. I've decided on wxpython for the GUI.... I've decided on...
8
by: Nathan Pinno | last post by:
Hi all, I need help figuring out how to fix my code. I'm using Python 2.2.3, and it keeps telling me invalid syntax in the if name == "Nathan" line. Here is the code if you need it. #This...
0
by: Jon Monteleone | last post by:
Greetings, I posted a few days back and didnt get much of a response, so I figured I would post again with more detail. I am running gnome under fedora core 4. I want a kid to be able to drop a...
2
by: wipit | last post by:
I need to process a HTML form in python. I'm using urllib2 and HTMLParser to handle the html. There are several steps I need to take to get to the specific page on the relevant site the first of...
8
by: LaundroMat | last post by:
Hi, I've found this script over at effbot (http://effbot.org/librarybook/os-path.htm), and I can't get my head around its inner workings. Here's the script: import os class...
12
by: adamurbas | last post by:
ya so im pretty much a newb to this whole python thing... its pretty cool but i just started today and im already having trouble. i started to use a tutorial that i found somewhere and i followed...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
Oralloy
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,...

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.