Skip to content

Instantly share code, notes, and snippets.

@vermiculus
Created March 11, 2014 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vermiculus/9477877 to your computer and use it in GitHub Desktop.
Save vermiculus/9477877 to your computer and use it in GitHub Desktop.
#+Title: Solution for In-Class Lab 2014-03-10 (COSC 251 SP14.6PM)
#+Author: Sean Allred and Molly Domino
#+Date: 2014-03-10
#+Objective: Read in a CSV, parse it as an adjacency matrix,
#+ and convert into an adjacency list.
# pretty-printing facilities
from pprint import pprint
print('Method 1: 21 lines of code (nothing fancy)')
lines = list()
try: # Read file
f = open('graph.csv')
lines = f.readlines()
f.close()
except IOError:
print("File doesn't exist?")
split_lines = list() # Parse as matrix
for l in lines:
split_lines.append(l.strip().split(','))
adj_list = dict() # Parse into adjacency list
for row in range(len(split_lines)):
for col in range(len(split_lines[row])):
edge_char = split_lines[row][col].strip()
if col > 0 and row is 0: # Header rows and columns
adj_list[edge_char] = list()
elif col > 0 and row > 0:
col_char = split_lines[0][col]
row_char = split_lines[row][0]
if int(edge_char): # if edge_char is '1', add to list
adj_list[row_char].append(col_char.strip())
pprint(adj_list)
print('Method 2: 12 lines of code (lambdas, mapping, comprehensions, and slicing)')
matrix = None
try:
with open('graph.csv') as f:
# Read all lines in file, splitting them at commas
matrix = [line.split(',') for line in f.readlines()]
except IOError: print("File doesn't exist?")
# Strip every element of every row in our matrix
matrix = [map(lambda s: s.strip(), row) for row in matrix]
# Construct an adjacency list from the very first row
adj_list2 = {node: list() for node in matrix[0][1:]}
# Iterate through
for row in matrix[1:]:
col_idx = 1
for el in row[1:]:
# if this element is not zero, then append the appropriate
# node to the list
if int(el): adj_list2[row[0]].append(matrix[0][col_idx])
col_idx += 1
pprint(adj_list2)
# Without comments, for comparison with Method 1
# matrix = None
# try:
# with open('graph.csv') as f:
# matrix = [line.split(',') for line in f.readlines()]
# except IOError: print("File doesn't exist?")
# matrix = [map(lambda s: s.strip(), row) for row in matrix]
# adj_list2 = {node: list() for node in matrix[0][1:]}
# for row in matrix[1:]:
# col_idx = 1
# for el in row[1:]:
# if int(el): adj_list2[row[0]].append(matrix[0][col_idx])
# col_idx += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment