import re import argparse def search(line, groups): #print("searching {} for {}".format(line, groups)) #find the first ? if not precheck(line, groups): return if check(line, groups): #print("found a solutioN!") yield line return if '?' not in line: return #print("delving into subtree {}".format(line.replace('?', '#', 1))) yield from search(line.replace('?', "#", 1), groups) yield from search(line.replace('?', ".", 1), groups) def precheck(line, groups): expected_hits = sum(groups) if line.count('#') > expected_hits: # if there are more hits in our candidate than the expected number, then this is a bad branch. # return false to skip it. #print("too many #") return False if line.count('.') > len(line) - expected_hits: # if there are moroe confirmed empties in our candidate than len - expected_hits, then this is a bad branch. # return false to skip it. #print("too many .") return False return True def check(line, groups): if '?' in line: return False line_list = list(map(lambda x: len(x), line.replace(".", " ").split())) if len(line_list) == len(groups): return all(map(lambda x: x[0] == x[1], zip(line_list, groups))) return False return groups == line_list parser = argparse.ArgumentParser() parser.add_argument("filename", help="the file from which to take data") args = parser.parse_args() with open(args.filename, "r") as f: line_re = re.compile("([.?#]*) ([0-9,]*)") s = 0 for l in f.readlines(): m = line_re.match(l) line = m.group(1) groups = list(map(int, m.group(2).split(','))) #print("line is {} and groups are {}".format(line, groups)) #for option in search(line, groups): # print(option) x = len(list(search(line,groups))) #print("there are {} solutinos".format(x)) s += x print("the total solutionss are {}".format(s)) print("and noow for part b") with open(args.filename, "r") as f: line_re = re.compile("([.?#]*) ([0-9,]*)") s = 0 for l in f.readlines(): m = line_re.match(l) line = m.group(1) line = line + "?" + line + "?" + line + "?" + line + "?" + line groups = list(map(int, m.group(2).split(','))) groups = groups * 5 print("line is {} and groups are {}".format(line, groups)) #for option in search(line, groups): # print(option) x = len(list(search(line,groups))) print("there are {} solutinos".format(x)) s += x print("the total solutionss are {}".format(s))