Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Input: lines like "<code>-<code>"
- # Output: largest connected set, sorted alphabetically, joined by commas
- connections = {}
- file = open("23_input.txt", "r")
- for line in file:
- line = line.replace("\n", "")
- parts = line.split("-")
- if not (parts[0] in connections):
- connections[parts[0]] = []
- connections[parts[0]].append(parts[1])
- if not (parts[1] in connections):
- connections[parts[1]] = []
- connections[parts[1]].append(parts[0])
- max_connections = 0
- for code in connections:
- if max_connections < len(connections[code]):
- max_connections = len(connections[code])
- def fully_connected(set):
- for i in range(len(set) - 1):
- for i2 in range(i + 1, len(set)):
- if not (set[i] in connections[set[i2]]):
- return False
- return True
- def subset_with_enough_connections(set, target_connections):
- if len(set) == target_connections:
- if fully_connected(set):
- return set
- else:
- return None
- for code in set:
- set2 = set.copy()
- set2.remove(code)
- subset = subset_with_enough_connections(set2, target_connections)
- if subset != None:
- return subset
- return None
- result = None
- target_connections = max_connections + 1
- while result == None:
- for code in connections:
- if len(connections[code]) < target_connections:
- continue
- set = connections[code].copy()
- set.append(code)
- result = subset_with_enough_connections(set, target_connections)
- if result != None:
- break
- target_connections -= 1
- result.sort()
- result_string = ""
- for code in result:
- result_string += "," + code
- print (result_string[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement