#!/bin/python3 import sys,time,re,os from pprint import pprint sys.path.insert(0, '../../') from fred import list2int,get_re,nprint,lprint,loadFile start_time = time.time() if sys.argv[1] == 'test': input_f = 'test' elif sys.argv[1] == 'input': input_f = 'input' else: print('No argv provided') exit() def loadList(input_f): lines = [] with open(input_f) as file: for line in file: lines.append(line.rstrip().split(',')) # Removes trailing newline from each line return lines[0] ######################################### # # # Part 1 # # # ######################################### def part1(): arr = loadList(input_f) score = 0 for a in arr: nums = list2int(re.split(r'-',a)) for x in range(nums[0],nums[1]+1): if len(str(x)) % 2 == 0: val = re.fullmatch(r'^(.+)\1$',str(x)) if val != None: score += int(val.group(0)) return score start_time = time.time() p1 = part1() print('Part 1:',p1, '\t\t', round((time.time() - start_time)*1000), 'ms') ######################################### # # # Part 2 # # # ######################################### def part2_slow(): # ~2400ms arr = loadList(input_f) score = 0 for a in arr: nums = list2int(re.split(r'-',a)) for x in range(nums[0],nums[1]+1): val = re.fullmatch(r'^(.+)\1+$',str(x)) if val != None: score += int(val.group(0)) def part2_regex_optimized(): # ~1200ms arr = loadList(input_f) score = 0 for a in arr: nums = list2int(re.split(r'-', a)) # Use regex but compile it once pattern = re.compile(r'^(.+)\1+$') for x in range(nums[0], nums[1] + 1): if pattern.fullmatch(str(x)): score += x return score def part2(): # ~4000ms arr = loadList(input_f) score = 0 for a in arr: nums = list2int(re.split(r'-',a)) skip = False for x in range(nums[0],nums[1]+1): str_len = len(str(x)) block = str_len // 2 for y in range(1,block+1): ###### adding this, made it ~3000ms if str_len % y != 0: continue ###### repeats = str_len // y if repeats < 2: continue r = str(x)[:y]*repeats #print('r: ',r,end=' ') if r == str(x): score += x break return score start_time = time.time() p2 = part2_regex_optimized() print('Part 2:',p2, '\t\t', round((time.time() - start_time)*1000), 'ms')