import sys # ----------------------------------------------------------- # getLines - Reads 'fileName' and returns an array of the # lines found in that file. Exits the program # if the file cannot be opened. # ----------------------------------------------------------- def getLines(fileName): try: f = open(fileName, "r") except IOError: print("Could not open file: [" + fileName + "]") sys.exit() content = f.readlines() f.close() list = [] for line in content: list.append(line.strip()) return(list) # ----------------------------------------------------------- # getElements - Our elements file contains both the element's # abbreviation and its full name, we want # only the abbreviation # ----------------------------------------------------------- def getElements(fileName): list = getLines(fileName) elements = [] for entry in list: value = entry.split() elements.append(value[0]) return(elements) # ----------------------------------------------------------- # Script Begins Here # ----------------------------------------------------------- elements = getElements("elements.txt") people = getLines("people.txt") nPeople = len(people) indices = [] options = [] for i in range(0, nPeople): indices.append(0) person = people[i].lower() list = [] for element in elements: if element.lower() in person: list.append(element) options.append(list) # ----------------------------------------------------- # To see the list of possible elements for each person # change 'False' to 'True' below # ----------------------------------------------------- if False: print(options) solutions = 0 while True: valid = True used = [] result = "" # ---------------------------------------------- # Ensure that no element appears more than once # in our result # ---------------------------------------------- for i in range(0, nPeople): element = options[i][indices[i]] if element in used: valid = False break else: used.append(element) result += ("" if result == "" else ", ") + element if valid: print(result) solutions += 1 # ---------------------------------------------- # Now, we want to increment our indices array # to refer to the next potential solution # ---------------------------------------------- i = nPeople - 1 while i >= 0: if indices[i] + 1 < len(options[i]): indices[i] += 1 break else: indices[i] = 0 i -= 1 if i < 0: break print("\nTotal: " + str(solutions))