def parse(): guests = set() edges = {} for line in input(13): m = re.match(r'^(\w+).*(lose|gain) (\d+).*\b(\w+).$', line) a, sign, amt, b = m.groups() amt = int(amt) if sign == 'lose': amt *= -1 edges[a, b] = amt guests.add(a) guests.add(b) return guests, edges
def input_data(root_path): for fp in com.all_files(root_path, EXCL_LIST): cur = com.file_stat(fp); db = com.select(fp); if cur['size'] < 100000000: # 100MB continue if db == None: h = com.hash(fp) if h != None : com.input(cur['path'], cur['size'], cur['date'], com.hash(fp)) print('등록',fp) continue # DB에 이미 등록되어 있고, 크기 및 날짜가 같다면 다음 if com.is_same_stat(cur, db) : print('이미 등록',fp) continue print('갱신',fp) com.update(cur['path'], cur['size'], cur['date'], com.hash(fp))
for x, y in self.get_points(p1, p2): self.ary[x][y] += 1 def turn_off(self, p1, p2): for x, y in self.get_points(p1, p2): v = self.ary[x][y] if v > 0: self.ary[x][y] = v - 1 def count_on(self): return sum(l for ln in self.ary for l in ln) # turn on 86,413 through 408,518 # toggle 340,102 through 918,558 # turn off 441,642 through 751,889 g = Grid() for line in input(6): cmd, p1, p2 = re.match(r'(^.+) (\d+,\d+) through (\d+,\d+)$', line).groups() p1 = tuple(map(int, p1.split(','))) p2 = tuple(map(int, p2.split(','))) if cmd == 'toggle': g.toggle(p1, p2) elif cmd == 'turn on': g.turn_on(p1, p2) elif cmd == 'turn off': g.turn_off(p1, p2) print(g.count_on())
from common import input import re import operator import string from pprint import pprint instructions = {} original = {} for line in input(7): cmd, wire = line.split(' -> ') instructions[wire.strip()] = cmd original[wire.strip()] = cmd def process(wire): inst = instructions[wire] if isinstance(inst, int): print(wire, inst) return inst else: inst = evaluate(inst) instructions[wire] = inst print(wire, inst) return inst def parse(instruction): m = re.match( r'^([\d|abcdefghijklmnopqrstuvwxyz]+)? ?(NOT|OR|AND|LSHIFT|RSHIFT)? ?([\d|\w]*)', instruction) a, op, b = m.groups()
def distance(position): return abs(position.imag) + abs(position.real) # part two: first place visited twice def first_visited_twice(s): dirs = [N, W, S, E] # start facing north parts = s.split(", ") total = [] position = (0 + 0j) visited = {} for p in parts: direction = p[0] distance = int(p[1:]) dirs = rotate_left(dirs) if direction == 'L' else rotate_right(dirs) for i in range(distance): visited[position] = True position += dirs[0] if visited.get(position, False): return position return position distance(moves(input(2016, 1).read())) distance(first_visited_twice(input(2016, 1).read()))
path.append(start) total += 1 break if start == last: print(start) exit() last = start if total % 1000 == 0: print(total) if total % 10000 == 0: print(start) return total, path if __name__ == '__main__': mappings, start = parse(input(19)) print(start) # # start = 'HOHOHOHHH' # mappings = { # 'H': {'HO','OH'}, # 'O': {'HH'}, # 'e': {'H', 'O'} # } # mappings = reverse_mappings(mappings) pprint(mappings) # print(get_possible_expansions(mappings, start)) moves = partial(get_possible_expansions, mappings)
from common import input from itertools import combinations from functools import reduce total = 0 ribbon = 0 mul = lambda s: reduce(lambda x, y: x * y, s) for l, w, h in (map(int, line.split('x')) for line in input(2)): sides = list(map(mul, combinations((l, w, h), 2))) total += sum(sides) * 2 + min(sides) perim_smallest = min((a + b) * 2 for a, b in combinations((l, w, h), 2)) vol = mul((l, w, h)) ribbon += perim_smallest + vol print(total, ribbon)
_min = sent k_min = ks if __name__ == '__main__': from itertools import chain from common import input from functools import reduce import sys try: groups = int(sys.argv[1]) except IndexError: groups = 4 nums = set(int(n) for n in input(24)) test = set(chain(range(1, 6), range(7, 12))) possibles = distribute(nums, groups) product = lambda s: reduce(lambda a, b: a * b, s) c_min = running_min(key=lambda s: (len(s), product(s))) next(c_min) max_l = 0 p_min = 0 _min = None for i, p in enumerate(possibles): _min = c_min.send(p) if not i % 1000 or p_min != _min: max_l = max(max_l, len(str(p))) print('{:{max_l}} {}'.format(str(p), str(_min), max_l=max_l + 1)) p_min = _min
from common import input from collections import Counter move_deltas = { '^': (0, 1), '>': (1, 0), 'v': (0, -1), '<': (-1, 0), } houses = [(0, 0), (0, 0)] for m in input(3).read(): try: delta = move_deltas[m] except KeyError: continue current = houses[-2] x, y = current dx, dy = delta houses.append((x + dx, y + dy)) c = Counter(houses) print(len(c))
for idx in range(len(T_0)): # T_0 と T の各行を配列に変換 t_0 = T_0[idx].strip().split(',') t = T[idx].strip().split(',') # 簡易 DEL チェッカー if t_0[0] == 'DEL': continue try: fl_t5 = float(t[5]) fl_t05 = float(t_0[5]) if fl_t5 < 0 or fl_t05 < 0: raise Exception # 値段の比率を罰則に加える. price_score += (1-min(fl_t5, fl_t05)/max(fl_t5, fl_t05)) except: sys.exit("Price wrong format") # 正規化 最高0.0 最低1.0 price_score = round(float(price_score)/float(len(T_0)),10) return price_score if __name__ == '__main__': # 入力の受け取り M,T,T_0 = common.input(3) # 有用性評価 price_score = eval(M,T,T_0) print(price_score, 'ut_price',sep=",")
pass for sue in to_delete: del data[sue] return data bounds = """children, EQ, 3 cats, GT, 7 samoyeds, EQ, 2 pomeranians, LT, 3 akitas, EQ, 0 vizslas, EQ, 0 goldfish, LT, 5 trees, GT, 3 cars, EQ, 2 perfumes, EQ, 1""" data = parse(input(16)) ops = { 'GT': operator.gt, 'EQ': operator.eq, 'LT': operator.lt, } for line in bounds.splitlines(): name, cmp, value = line.split(', ') value = int(value) cmp = ops[cmp] data = filter_by_property(data, name, cmp, value) pprint(data) print(len(data))
from common import input from collections import Counter from my_utils.decorators import memo def parse(infile): return sorted(int(l.strip()) for l in infile) coins = parse(input(17)) target = 150 #test data # coins = 20, 10, 15, 5, 5 # target = 25 depths = Counter() def recursive_solution(coinsleft, target, depth=0): if target == 0: depths[depth] += 1 return 1 if target < 0: return 0 solutions = 0 used = set() for coin in coinsleft: used.add(coin) solutions += recursive_solution(coinsleft - used, target - coin[1], depth + 1)
import re from common import input original = in_mem = 0 for line in input(8): line = bytes(line.strip(), 'UTF8') original += len(line) in_mem += len(eval(line)) print(original - in_mem) new = 0 for line in input(8): line = bytes(line.strip(), 'UTF8') new += len(re.escape(line)) + 2 print(new - original)
yield (total_weight, ) else: for w in range(total_weight + 1): for remainder in ratios(num_ings - 1, total_weight - w): yield (w, ) + remainder def calc_score(ingredients, ratio): num_attribs = len(next(iter(ingredients.values()))) attribs = {i: 0 for i in range(num_attribs)} for ing, r in zip(ingredients.values(), ratio): for i in range(num_attribs): attribs[i] += ing[i] * r for at in attribs: if attribs[at] < 0: attribs[at] = 0 if attribs[num_attribs - 1] != 500: return 0 return reduce(lambda x, y: x * y, list(attribs.values())[:-1]) ingredients = parse(input(15)) pprint(ingredients) best = 0 for ratio in ratios(len(ingredients), 100): score = calc_score(ingredients, ratio) if score > best: best = score print(best)
def is_nice2(s): pair_count = Counter() repeat = False for i, c in enumerate(s): try: pair_count[s[i:i + 2]] += 1 if s[i:i + 3] == c * 3 and s[i:i + 4] != c * 4: pair_count[s[i:i + 2]] -= 1 except IndexError: pass try: if c == s[i + 2]: repeat = True except IndexError: pass if repeat and max(pair_count.values()) > 1: return True else: return False print(sum(is_nice2(s) for s in input(5))) assert is_nice2('qjhvhtzxzqqjkmpb') assert is_nice2('xxyxx') assert not is_nice2('uurcxstgmygtbstg') assert not is_nice2('ieodomkazucvgmuy') assert is_nice2('aaaaba')
while time > 0: if flying: chunk = r.fly_time else: chunk = r.rest_time if time < chunk: distance += r.speed * time * flying time -= time else: distance += r.speed * chunk * flying time -= chunk flying = not flying return distance reindeer = parse(input(14)) print('winning distance: ', max(map(get_distance_after_t, reindeer))) score = {r: 0 for r in reindeer} for t in range(1, 2504): scores = [] best = 0 for r in reindeer: d = get_distance_after_t(r, t) scores.append(d) if d > best: best = d for r, s in zip(reindeer, scores): if s == best: score[r] += 1 pprint(score)
from common import input moves = input(1).read() floor = 0 position = 0 for m in moves: position += 1 if m == '(': floor += 1 elif m == ')': floor -= 1 if floor < 0: print("basement at positon ", position) break print(floor)
} pprint(instructions) while i < len(instructions): cmd, *args = instructions[i] print(instructions[i]) mapping[cmd](*args) i += 1 print(reg, i) return reg def parse(instructions): def make_ints(s): try: return int(s) except ValueError: return s instructions = (re.split(r',?\s', l.strip()) for l in instructions) return [tuple(make_ints(p) for p in i) for i in instructions] if __name__ == '__main__': cmds = input(23) print(interpret(cmds))
def guess_ini(M): guess = OrderedDict() for idx in range(len(M)): guess[M[idx].strip().split(',')[0]] = ['DEL' for i in range(12)] return guess def eval(M, T_sub, S): sig_S = sig_gen(S, ATTR) guess = guess_ini(M) for idx in range(len(T_sub)): t_sub_gyo = T_sub[idx].strip().split(',') value= ':'.join([t_sub_gyo[i] for i in range(len(t_sub_gyo)) if i in ATTR]) cus_id = t_sub_gyo[0] if value in sig_S.keys(): guess[cus_id][month_passed(t_sub_gyo[2])]=sig_S[value] return [cus_id+","+",".join(guess[cus_id]) for cus_id in guess.keys()] def drop(S, num): for idx in range(len(S)): S_gyo = S[idx].strip().split(',') S_gyo[4] = S_gyo[4][0:min(len(S_gyo[4]), num)] S[idx] = ','.join(S_gyo) return S if __name__ == '__main__': M,S,T_sub = common.input(3) if 4 in ATTR: # 4は商品IDについての属性 S = drop(S, 2) common.output([eval(M, T_sub, S)])
from common import input import re from itertools import permutations edge = {} cities = set() for line in input(9): m = re.match(r'^(\w+) to (\w+) = (\d+)$', line) a, b, dist = m.groups() cities.add(a) cities.add(b) dist = int(dist) edge[a, b] = edge[b, a] = int(dist) def salesman(longest=False): best = float('inf') if not longest else 0 for p in permutations(cities): s = 0 for i, c in enumerate(p): try: s += edge[c, p[i+1]] except IndexError: pass if not longest and s < best: best = s elif longest and s > best: best = s return best print('shortest: ', salesman())