Created
September 16, 2014 05:51
-
-
Save aks/9fb0b7b06a8a6b1d5ac0 to your computer and use it in GitHub Desktop.
Python script to read a list of node pairs and output the list of node neighbors.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# nodes <infile | |
# | |
# Read in lists of node neighbors, and output complete list of all neighbors | |
# | |
# Input: | |
# | |
# 0 1 | |
# 1 2 | |
# 2 3 | |
# 3 4 | |
# 4 0 | |
# 4 1 | |
# 5 3 | |
# | |
# Output: | |
# [[1, 4], [0, 2, 4], [1, 3], [2, 4, 5], [0, 1, 3], [3]] | |
class NodeList: | |
def __init__(self): | |
self.nodes = {} | |
def add_pair(self, n1, n2): | |
self.add_node(n1, n2) | |
self.add_node(n2, n1) | |
def add_node(self, n1, n2): | |
if n1 not in self.nodes: | |
self.nodes[n1] = [] | |
if n2 not in self.nodes[n1]: # add n2 only if not already a link | |
self.nodes[n1].append(n2) | |
def neighbors(self): | |
return list(map(lambda k: sorted(self.nodes[k]), sorted(self.nodes.keys()))) | |
nodes = NodeList() | |
while True: | |
try: | |
line = input() | |
nums = [int(x) for x in line.split()] | |
if len(nums) > 0: | |
n1 = nums.pop(0) | |
for nx in nums: | |
nodes.add_pair(n1, nx) | |
except EOFError: | |
break | |
print(nodes.neighbors()) | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment