Teodorico Levoff - 7 months ago 42

Python Question

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)))`

`LIST OF ARCS`

0 1 0.440004

0 2 0.244452

0 3 0.433273

For the input above, the output should be

`ListBuffer(`

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

```
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(']', ')'))
```

Source (Stackoverflow)