Skip to content

Commit 44c90c7

Browse files
committed
Test program for algorithm to solve problem of combining multiple sorted lists.
1 parent 8382f89 commit 44c90c7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

topNmultiList.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import heapq
2+
3+
class Row():
4+
data = []
5+
def __init__( self, idx ):
6+
self.idx = list(idx)
7+
self.tot = 0.0
8+
for dd, ii in zip( self.data, idx ):
9+
self.tot += dd[ ii ]
10+
11+
def print( self ):
12+
for ii, dd in zip( self.idx, self.data ):
13+
print( "{:8.1f}".format( dd[ii] ), end = "" )
14+
print( "{:8.1f}".format( self.tot ) )
15+
16+
def __lt__( self, other ):
17+
if self.tot < other.tot:
18+
return True
19+
elif self.tot == other.tot:
20+
return self.idx < other.idx
21+
return False
22+
23+
def __eq__( self, other ):
24+
return self.idx == other.idx
25+
26+
def main():
27+
a = sorted([1, 1.2, 1.5, 2, 2.1, 4, 5, 5.5 ])
28+
b = sorted([10, 10.1, 10.4, 10.8, 12.1, 13, 15, 15.5 ])
29+
c = sorted([100, 100.5, 100.6, 101.8, 102.1, 102.3, 104, 107 ])
30+
Row.data = [a, b, c]
31+
32+
33+
vec = [Row( [0, 0, 0] )]
34+
heapq.heapify( vec )
35+
36+
svec = []
37+
38+
aii = 0
39+
bii = 0
40+
cii = 0
41+
42+
while( len( svec ) < 20 ):
43+
print( len( vec ), len( svec ) )
44+
rr = heapq.heappop( vec )
45+
if len( vec ) > 0 and not rr == vec[0]:
46+
svec.append( rr )
47+
for ii in range( len( Row.data ) ):
48+
idx2 = list(rr.idx)
49+
idx2a = list(idx2)
50+
idx2[ii] += 1
51+
print( idx2a, idx2, ii )
52+
heapq.heappush( vec, Row( idx2 ) )
53+
54+
55+
for vv in sorted(svec):
56+
vv.print()
57+
58+
if __name__ == "__main__":
59+
main()

0 commit comments

Comments
 (0)