Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2024
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. # Input: lines like "<code>-<code>"
  2. # Output: largest connected set, sorted alphabetically, joined by commas
  3.  
  4. connections = {}
  5.  
  6. file = open("23_input.txt", "r")
  7. for line in file:
  8.   line = line.replace("\n", "")
  9.   parts = line.split("-")
  10.   if not (parts[0] in connections):
  11.     connections[parts[0]] = []
  12.   connections[parts[0]].append(parts[1])
  13.   if not (parts[1] in connections):
  14.     connections[parts[1]] = []
  15.   connections[parts[1]].append(parts[0])
  16.  
  17. max_connections = 0
  18. for code in connections:
  19.   if max_connections < len(connections[code]):
  20.     max_connections = len(connections[code])
  21.  
  22. def fully_connected(set):
  23.   for i in range(len(set) - 1):
  24.     for i2 in range(i + 1, len(set)):
  25.       if not (set[i] in connections[set[i2]]):
  26.         return False
  27.   return True
  28.  
  29. def subset_with_enough_connections(set, target_connections):
  30.   if len(set) == target_connections:
  31.     if fully_connected(set):
  32.       return set
  33.     else:
  34.       return None
  35.   for code in set:
  36.     set2 = set.copy()
  37.     set2.remove(code)
  38.     subset = subset_with_enough_connections(set2, target_connections)
  39.     if subset != None:
  40.       return subset
  41.   return None
  42.  
  43. result = None
  44. target_connections = max_connections + 1
  45. while result == None:
  46.   for code in connections:
  47.     if len(connections[code]) < target_connections:
  48.       continue
  49.     set = connections[code].copy()
  50.     set.append(code)
  51.     result = subset_with_enough_connections(set, target_connections)
  52.     if result != None:
  53.       break
  54.   target_connections -= 1
  55.  
  56. result.sort()
  57. result_string = ""
  58. for code in result:
  59.   result_string += "," + code
  60. print (result_string[1:])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement