コード例 #1
0
def prep_input(raw_data):
    # extract timestamps
    log = []
    for line in raw_data:
        timestamp, action = line[:18], line[19:]
        timestamp = [abs(i) for i in parse_int(timestamp)]
        timestamp = pm.datetime(*timestamp)
        log.append((timestamp, action))

    # Separate by guard on duty, and generate minutes they were asleep
    log.sort()

    guard_id = None
    nap_start = None
    guard_nap_minutes = {}
    for timestamp, action in log:
        if parse_int(action):
            guard_id = parse_int(action)[0]
        elif action.endswith("falls asleep"):
            nap_start = timestamp
        elif action.endswith("wakes up"):
            duration = timestamp - nap_start
            # drop last one, which is when they wake up
            minutes = [ts.minute for ts in duration.range("minutes")][:-1]

            guard_log = guard_nap_minutes.setdefault(guard_id, [])
            guard_log.extend(minutes)

    return guard_nap_minutes
コード例 #2
0
ファイル: weight.py プロジェクト: spr3nk3ls/koert
	def from_line(cls, line, productdir):
		if len(line)<3:
			raise ValueError("weight line is too small")
		product_str, empty_str, full_str = line[0:3]
		product = productdir[product_str]
		full = parse_int(full_str)
		empty = parse_int(empty_str)
		return cls(product, full, empty)
コード例 #3
0
 def from_line(cls, line, boozedir):
     if len(line) < 1:
         raise ValueError("product line is too small: '%s' " % (line,))
     handle, name = line[0:2]
     factors = {}
     for i in xrange(2, len(line)):
         field = line[i]
         if field == "":
             break
         comps = field.split(":")
         if len(comps) != 2:
             raise ValueError(
                 "error in factor multiple's"
                 " formatting; components: "
                 " %s " % (comps,) + "; "
                 "did you forget a colon?"
             )
         amount_str, factor_name = comps
         amount = parse_int(amount_str)
         factor = boozedir.factordir[factor_name]
         if factor in factors:
             raise ValueError("factor occurs twice")
         factors[factor] = amount
     if len(factors) == 0:
         raise MildErr("product %s (%s) has no factors" % (handle, name))
     return cls(handle=handle, name=name, factors=Count(factors, parse_amount))
コード例 #4
0
def parse_and_validate_array_elements(string: str, element_count: int):
    splits = string.split()
    validate_length(splits, element_count)
    validate_if_all_numbers(splits)
    for part in splits:
        validate_range(parse_int(part), 0, 10**6)
    return splits
コード例 #5
0
ファイル: day6.py プロジェクト: hassanshamim/adventofcode
def test_example_part1():
    example = """1, 1
                1, 6
                8, 3
                3, 4
                5, 5
                8, 9""".splitlines()
    example = [parse_int(line) for line in example]
    result = part1(data=example)
    assert result == 17
コード例 #6
0
ファイル: event.py プロジェクト: spr3nk3ls/koert
	def from_str(cls, s):
		# The grammar:  <number>[/<label>]
		s = s.strip()
		if not s:
			return cls()
		parts = s.split("/",1)
		number = parse_int(parts[0])
		if len(parts)==1:
			return cls(number)
		label = parts[1]
		return cls(number,label)
コード例 #7
0
ファイル: day16.py プロジェクト: hassanshamim/adventofcode
def part1(instructions=PUZZLE_INPUT, progs=None):
    if progs is None:
        progs = list('abcdefghijklmnop')

    for line in instructions:
        cmd = line.startswith
        if cmd('x'):
            a, b = parse_int(line)
            progs[b], progs[a] = progs[a], progs[b]
        elif cmd('p'):
            a, b = line[1], line[3]
            ai, bi = progs.index(a), progs.index(b)
            progs[ai], progs[bi] = progs[bi], progs[ai]
        elif cmd('s'):
            n = int(line[1:])
            progs = progs[-n:] + progs[:-n]

    return ''.join(progs)
コード例 #8
0
 def from_input(cls, line):
     """Create new Particle object from puzzle input"""
     *data, _trash = line.split('>')
     data = [parse_int(triplet) for triplet in data]
     return cls(*data)
コード例 #9
0
 def parse_gewogen(self, args_str):
     weighed = parse_int(args_str)
     if self.weight == None:
         raise MildErr("missing weight for %r" % self)
     return self.weight.weighed_to_fraction(weighed)
コード例 #10
0
"https://adventofcode.com/2018/day/3"

from common import puzzle_input, parse_int

from collections import Counter

PUZZLE_INPUT = [parse_int(line) for line in puzzle_input(3)]


def square_inch_ids(x_offset, y_offset, width, height):
    """
    generates a series representing the ids each
    square inch of fabric used for this claim
    """
    start = y_offset * 1000 + x_offset
    for i in range(width):
        for j in range(height):
            yield start + i + (j * 1000)


def part1(data=PUZZLE_INPUT):
    square_count = Counter()

    for _id, *square in PUZZLE_INPUT:
        square_count.update(square_inch_ids(*square))

    return sum(count > 1 for count in square_count.values())


def part2(data=PUZZLE_INPUT):
    claim_ids = set()