def __divide(i, lo, hi, b4, rank):
        "Find a split between lo and hi, then recurse on each split."

        if i.yis == "Num":
            l = i.numSplit([])
            r = i.numSplit(i._lst[lo:hi])
            i.stop = last(b4.inits)
            i.start = first(b4.inits)
        else:
            l = i.symSplit([])
            r = i.symSplit(i._lst[lo:hi])
            i.stop = last(b4.symList)
            i.start = first(b4.symList)

        i.epsilon = b4.variety() * THE.div.cohen
        best = b4.variety()
        cut = None
        for j in range(lo, hi):
            l.add(i._lst[j])
            r.sub(i._lst[j])

            if l.n >= i.step:
                if r.n >= i.step:
                    now = i._lst[j - 1]
                    after = i._lst[j]
                    if now == after: continue
                    # print("yis", i.yis, lo)
                    if i.yis == "Num":
                        if abs(r.mu - l.mu) >= i.epsilon:
                            if after - i.start >= i.epsilon:
                                if i.stop - now >= i.epsilon:
                                    xpect = l.xpect(r)
                                    if xpect * THE.div.trivial < best:
                                        best, cut = xpect, j
                    else:
                        # print("Modes: ", r.mode, l.mode, lo)
                        if abs(ord(r.mode) - ord(l.mode)) >= i.epsilon:
                            if ord(after) - ord(i.start) >= i.epsilon:
                                if ord(i.stop) - ord(now) >= i.epsilon:
                                    xpect = l.xpect(r)
                                    if xpect * THE.div.trivial < best:
                                        best, cut = xpect, j

        if cut:
            ls, rs = i._lst[lo:cut], i._lst[cut:hi]
            # print("values:",lo, cut)
            i.finalcut = cut
            i.finallow = lo
            if i.yis == "Num":
                rank = i.__divide(lo, cut, i.numSplit(ls), rank) + 1
                rank = i.__divide(cut, hi, i.numSplit(rs), rank)
            else:
                rank = i.__divide(lo, cut, i.symSplit(ls), rank) + 1
                rank = i.__divide(cut, hi, i.symSplit(rs), rank)
        else:
            i.gain += b4.n * b4.variety()
            i.ranges += [b4]
        return rank
Exemple #2
0
def get_info(cover_html):
    """Return dictionary with the book info (prefix, page_ids, title, attribution)."""
    tag = lib.first(s for s in cover_html.split("<")
                    if re.search('input[^>]*\s+name="?ie"?', s))
    if tag:
        match = re.search('value="(.*?)"', tag)
        if not match:
            raise ParsingError, "Cannot found encoding info"
        encoding = match.group(1).lower()
    else:
        encoding = "iso8859-15"
    match = re.search(r'_OC_Run\((.*?)\);', cover_html)
    if not match:
        raise ParsingError, "No JS function OC_Run() found in HTML"
    oc_run_args = json.loads("[%s]" % match.group(1), encoding=encoding)
    if len(oc_run_args) < 2:
        raise ParsingError, "Expecting at least 2 arguments in function OC_Run()"
    pages_info, book_info = oc_run_args[:2]
    page_ids = [
        x["pid"] for x in sorted(pages_info["page"], key=lambda d: d["order"])
    ]
    if not page_ids:
        raise ParsingError, "No page_ids found"
    prefix = pages_info["prefix"].decode("raw_unicode_escape")
    return {
        "prefix": prefix,
        "page_ids": page_ids,
        "title": book_info["title"],
        "attribution": re.sub("^By\s+", "", book_info["attribution"]),
    }
Exemple #3
0
def get_info(cover_html):
    """Return dictionary with the book info (prefix, page_ids, title, attribution)."""
    tag = lib.first(s for s in cover_html.split("<")
        if re.search('input[^>]*\s+name="?ie"?', s))
    if tag:
        match = re.search('value="(.*?)"', tag)
        if not match:
            raise ParsingError, "Cannot found encoding info"
        encoding = match.group(1).lower()
    else:
        encoding = "iso8859-15"
    match = re.search(r'_OC_Run\((.*?)\);', cover_html)
    if not match:
        raise ParsingError, "No JS function OC_Run() found in HTML"
    oc_run_args = json.loads("[%s]" % match.group(1), encoding=encoding)
    if len(oc_run_args) < 2:
        raise ParsingError, "Expecting at least 2 arguments in function OC_Run()"
    pages_info, book_info = oc_run_args[:2]
    if "page" not in pages_info:
      raise ParsingError, "Cannot found page info"
    page_ids = [x["pid"] for x in sorted(pages_info["page"], key=lambda d: d["order"])]
    if not page_ids:
        raise ParsingError, "No page_ids found"
    prefix = pages_info["prefix"].decode("raw_unicode_escape")
    mw = book_info["max_resolution_image_width"]
    mh = book_info["max_resolution_image_height"]
    return {
        "prefix": prefix,
        "page_ids": page_ids,
        "title": get_unescape_entities(book_info["title"]),
        "attribution": get_unescape_entities(re.sub("^By\s+", "", book_info["attribution"])),
        "max_resolution": (mw, mh),
    }
    def __init__(i, lst, x=first, xis=Num, y=last, yis=Num):
        i.x, i.xis = x, xis
        i.y, i.yis = y, yis
        # print("LIST: ", lst)
        # print("LIST: ", i.y, i.yis)
        # i._lst     = list(map(lambda x: x.cells, lst))
        # i._lst     = ordered(lst,key=x)
        i._lst = lst  # we need this or row tobe ordered
        i._lst.sort(key=lambda test_list: test_list.cells[0])

        # print("LIST: ", i._lst)
        i.xs = i.xis(i._lst, key=x)
        i.ys = i.yis(i._lst, key=y)
        i.gain = 0  # where we will be, once done
        i.step = int(len(
            i._lst)**THE.div.min)  # each split need >= 'step' items
        i.stop = x(last(i._lst))  # top list value
        i.start = x(first(i._lst))  # bottom list value
        i.ranges = []  # the generted ranges
        i.epsilon = i.xs.sd(
        ) * THE.div.cohen  # bins must be seperated >= epsilon
        i.finalcut = 0
        i.finallow = 0

        i.__divide(1, len(i._lst), i.xs, i.ys, 1)
Exemple #5
0
 def __init__(i, lst, x="first", y="last", yis="Num"):
     i.yis = yis
     i.x_lst, i.y_lst = i.createXYList(lst, yis)
     i.b4 = i.y_lst
     i._lst = i.y_lst.numList if i.yis == "Num" else i.y_lst.symList
     i.gain = 0  # where we will be, once done
     i.step = int(i.y_lst.n**THE.div.min)  # each split need >= 'step' items
     i.stop = last(i.y_lst.numList) if i.yis == "Num" else last(
         i.y_lst.symList)  # top list value
     i.start = first(i.y_lst.numList) if i.yis == "Num" else first(
         i.y_lst.symList)  # bottom list value
     i.ranges = []  # the generted ranges
     i.epsilon = i.y_lst.variety(
     ) * THE.div.cohen  # bins must be seperated >= epsilon
     i.__divide(0, i.b4.n, i.b4, 1)
     i.gain /= len(i._lst)
     i.splitXList()
Exemple #6
0
 def __init__(i, lst, x=same, xis=Num):
     i.xis = xis
     i._lst = ordered(lst, key=x)
     i.b4 = i.xis(i._lst, key=x)
     i.gain = 0  # where we will be, once done
     i.x = x  # how to get values from 'lst' items
     i.step = int(len(
         i._lst)**THE.div.min)  # each split need >= 'step' items
     i.stop = x(last(i._lst))  # top list value
     i.start = x(first(i._lst))  # bottom list value
     i.ranges = []  # the generted ranges
     i.epsilon = i.b4.sd(
     ) * THE.div.cohen  # bins must be seperated >= epsilon
     i.__divide(1, len(i._lst), i.b4, 1)
     i.gain /= len(i._lst)
Exemple #7
0
 def __init__(self, lst, x=first, y=last, yis=Num):
     self.ctype = yis
     self.x = x
     self.y = y
     self.lst = ordered(lst, key=x)
     self.xtype = Num(self.lst, key=x)
     self.ytype = self.ctype(self.lst, key=y)
     self.gain = 0  # where we will be, once done
     #i.x = x  # how to get values from 'lst' items
     self.step = int(len(
         self.lst)**THE.div.min)  # each split need >= 'step' items
     self.stop = x(last(self.lst))  # top list value
     self.start = x(first(self.lst))  # bottom list value
     self.ranges = []  # the generted ranges
     self.epsilon = self.xtype.sd(
     ) * THE.div.cohen  # bins must be seperated >= epsilon
     self.divide(1, len(self.lst), 1)
     self.gain /= len(self.lst)
Exemple #8
0
def solve(recipes: Recipes) -> List[Tuple[Allergen, Ingredient]]:
    possible_allergens = could_be(recipes)

    found_allergens: List[Tuple[Allergen, Ingredient]] = []
    while possible_allergens:
        new_known_allergens = [
            allergen for allergen, ingredients in possible_allergens.items()
            if len(ingredients) == 1
        ]
        for allergen in new_known_allergens:
            allergic_ingredient = lib.first(possible_allergens[allergen])
            found_allergens.append((allergen, allergic_ingredient))

            for other_allergen in possible_allergens:
                possible_allergens[other_allergen].discard(allergic_ingredient)

            possible_allergens.pop(allergen)

    return found_allergens
Exemple #9
0
def get_info(cover_html):
    """Return dictionary with the book information.

    Include the prefix, page_ids, title and attribution."""
    tag = lib.first(s for s in cover_html.split("<")
                    if re.search('input[^>]*\s+name="?ie"?', s))
    if tag:
        match = re.search('value="(.*?)"', tag)
        if not match:
            raise ParsingError('Cannot find encoding info')
        encoding = match.group(1).lower()
    else:
        encoding = "iso8859-15"
    match = re.search(r'_OC_Run\((.*?)\);', cover_html)
    if not match:
        raise ParsingError('No JS function OC_Run() found in HTML')
    oc_run_args = json.loads("[%s]" % match.group(1), encoding=encoding)
    if len(oc_run_args) < 2:
        raise ParsingError('Expecting at least 2 arguments in function: '
                           'OC_Run()')
    pages_info, book_info = oc_run_args[:2]
    if "page" not in pages_info:
        raise ParsingError('Cannot find page info')
    page_ids = [
        x["pid"] for x in sorted(pages_info["page"], key=lambda d: d["order"])
    ]
    if not page_ids:
        raise ParsingError('No page_ids found')
    prefix = pages_info["prefix"].decode("raw_unicode_escape")
    mw = book_info["max_resolution_image_width"]
    mh = book_info["max_resolution_image_height"]
    return {
        "prefix":
        prefix,
        "page_ids":
        page_ids,
        "title":
        get_unescape_entities(book_info["title"]),
        "attribution":
        get_unescape_entities(re.sub("^By\s+", "", book_info["attribution"])),
        "max_resolution": (mw, mh),
    }
Exemple #10
0
 def __init__(self, lst, x, y, ctypes, key_fn=same):
     self.ctypes = ctypes
     self.key_fn = key_fn
     self.lst = ordered(lst, key="", index=x)
     self.b4 = [class_type("", idx) for idx, class_type in enumerate(self.ctypes)]
     for row in self.lst:
         for idx, val in enumerate(row):
             self.b4[idx].addVal(val)
     self.x = x
     self.y = y
     self.step = int(len(self.lst)) ** THE.div.min
     self.gain = 0
     self.start = first(self.b4[self.y].all_values)
     self.stop = last(self.b4[self.y].all_values)
     self.ranges = []
     self.epsilon = self.b4[self.y].variety()
     self.epsilon *= THE.div.cohen
     low = 1
     high = self.b4[self.y].n
     self.rank, self.cut, self.best = self.divide(1, low, high, self.b4)
     self.gain /= self.b4[self.y].n
Exemple #11
0
def part_2(raw: str):
    tiles = parse_input(raw)
    size = int(len(tiles)**0.5)
    shared_edges: EdgeMap = get_shared_edges(tiles)
    tlc = lib.first(get_corners(tiles))

    top_left_edges = shared_edges[tlc].keys()
    while tlc.bottom() not in top_left_edges or tlc.right(
    ) not in top_left_edges:
        tlc = tlc.rotate()

    tile_grid: List[List[ImageTile]] = [[tlc]]

    for i in range(size - 1):
        current_tile = tile_grid[-1][0]

        key_tile = lib.first(current_tile.variations(),
                             lambda v: v in shared_edges)

        downwards_tile = shared_edges[key_tile][current_tile.bottom()]
        variation = lib.first(downwards_tile.variations(),
                              lambda v: v.top() == current_tile.bottom())

        assert variation.top() == current_tile.bottom()
        tile_grid.append([variation])

    for row in tile_grid:
        for i in range(size - 1):
            current_tile = row[-1]

            key_tile = lib.first(current_tile.variations(),
                                 lambda v: v in shared_edges)

            rightwards_tile = shared_edges[key_tile][current_tile.right()]
            variation = lib.first(rightwards_tile.variations(),
                                  lambda v: v.left() == current_tile.right())

            assert current_tile.right() == variation.left()
            row.append(variation)

    for row in tile_grid:
        for t1, t2 in lib.window(row, 2):
            assert t1.right() == t2.left()

    for i in range(len(tile_grid)):
        column = [row[i] for row in tile_grid]
        for t1, t2 in lib.window(column, 2):
            assert t1.bottom() == t2.top()

    pixel_ids = [tile.tile_id for row in tile_grid for tile in row]
    assert len(set(pixel_ids)) == len(list(pixel_ids))

    tile_size = len(tiles[0].pixels)
    pixels: List[List[bool]] = []
    for row in tile_grid:
        for i in range(1, tile_size - 1):
            pixels.append([])
            for tile in row:
                for pixel in tile.pixels[i][1:-1]:
                    pixels[-1].append(pixel)

    mega_tile = ImageTile(1, tuple(tuple(row) for row in pixels))
    return min(map(count_monsters, mega_tile.variations()))
Exemple #12
0
def part2():
    rendered_pixel = lambda pixel_stack: first(pixel_stack, lambda p: p != 2)
    return map(rendered_pixel, zip(*get_input()))
Exemple #13
0
def xpath_node(from_node, xpath):
    """
     Return first node matching xpath from from_node as dom node. 
  """
    return LIB.first(xpath_list(from_node, xpath))
Exemple #14
0
def find_entries(entries: typing.Iterable[int], num_dimensions: int,
                 target: int) -> int:
    combinations = itertools.combinations(entries, num_dimensions)
    return lib.product(
        lib.first(combinations, lambda combo: sum(combo) == target))
Exemple #15
0
def find_min(m, prod, y, y_offset):
    possibilities = itertools.count(m, prod)
    return lib.first(possibilities, lambda num: (num + y_offset) % y == 0)