Teodorico Levoff Teodorico Levoff - 1 year ago 72
Python Question

Script to take long list of data and turn it into Scala lists?

I have a list of arcs(200lines max) in a graph like shown below. The triple is (x, y, z) which means an edge from x to y at weight z. I know exactly how many lines are in the file(number of edges), the number of nodes too. I want to create an adjacency matrix input with these edges in Scala using List from Scala. Syntax is like i.e for example

List(List(0,0,0,0), List(0,0,0,0)))
I want to have a script that can take in a .txt file of the form shown below and output Scala syntax of an adj. list from these edges.

0 1 0.440004
0 2 0.244452
0 3 0.433273

For the input above, the output should be

ListBuffer(0, 0.440004, 0.244452, 0.433273),
ListBuffer(0.440004, 0, 0, 0),
ListBuffer(0.244452, 0, 0, 0),
ListBuffer(0.433273, 0, 0, 0))

Here is what I have and my idea.
val lines = Source.fromFile("f1.txt").getLines.toList.map(i => println(i))
I can prefill a ListBuffer.fill(10)(10) and then if I can figure out how to make each line a triple of type Ints, then I can update the ListBuffer structure I prefilled.

Answer Source
with open('input.txt') as infile:
    lines = infile.readlines()[1:]  # skip header
edges = [line.split() for line in lines]
edges = [(int(t[0]), int(t[1]), float(t[2])) for t in edges]
n = max(max(edge[:2]) for edge in edges) + 1
matrix = [[0] * n for _ in range(n)]
for edge in edges:
    for x, y in [edge[:2], reversed(edge[:2])]:
        matrix[x][y] = edge[2]

print(str(matrix).replace('[', 'ListBuffer(').replace(']', ')'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download