def solve(limit, search_delta=0.3):
    lower = int(sqrt(limit) * (1 - search_delta))
    upper = int(sqrt(limit) * (1 + search_delta))
    primes = list(ibetween(gen_primes(), lower, upper))

    info(f"Searching using prime factors {lower} < p < {upper}")

    result_n, result_q = None, inf

    for factors in combinations(primes, 2):
        n = prod(factors)

        if n > limit:
            continue

        phi_n = phi(n)

        if is_permutation(n, phi_n):
            q = n / phi_n

            if q < result_q:
                result_n, result_q = n, q

            info(f"n = {n}\tphi(n) = {phi_n}\tn/phi(n) = {q}")

    return result_n
def solve(target):
    for a in range(1, target // 2):
        for b in range(a + 1, target // 2):
            for c in range(b + 1, target // 2):
                if a + b + c == target and a * a + b * b == c * c:
                    info(f"{a} + {b} + {c} = {target}")
                    return a * b * c
Beispiel #3
0
def getTop100Keywords(site, query, max):
    keywordDict = {}
    site = site.lower()
    count = 0
    q = queue.Queue(max + 1000)
    q.put(query)
    while not q.empty():
        if count == max:
            break
        else:
            count += 1

        keyword = q.get()

        relatedKeywords = []
        if site == 'naver':
            relatedKeywords = search.searchRelatedKeywordNaver(keyword)
        elif site == 'daum':
            relatedKeywords = search.searchRelatedKeywordDaum(keyword)
        elif site == 'google':
            relatedKeywords = search.searchRelatedKeywordGoogle(keyword)

        log.info(keyword + ': ' + ','.join(relatedKeywords))

        for relatedKeyword in relatedKeywords:
            if relatedKeyword == query:
                continue
            elif relatedKeyword in keywordDict.keys():
                keywordDict[relatedKeyword] += 1
            else:
                keywordDict[relatedKeyword] = 1
                q.put(relatedKeyword)

    return keywordDict
Beispiel #4
0
def fetch(url):
    '''
    return arbitrary URL data
    '''
    filename = posixpath.split(url)[-1]
    logging.info('attempting to fetch %s', filename)
    filepath = os.path.join(STORAGE, filename)
    if filename.endswith(".zip"):
        unzippedname = filename[:-4]
        unzippedpath = os.path.join(STORAGE, unzippedname)
        if os.path.exists(unzippedpath):
            logging.debug('found cached content %s', unzippedpath)
            with open(unzippedpath, 'rb') as infile:
                return infile.read()
    if not os.path.exists(filepath):
        logging.info('fetching %s', url)
        with urlopen(url) as infile:
            with open(filepath, 'wb') as outfile:
                outfile.write(infile.read())
    if filename.endswith(".zip"):
        zipped = zipfile.ZipFile(filepath)
        with zipped.open(unzippedname, 'r') as datafile:  # 'rb' not accepted
            data = datafile.read()
            logging.debug('caching %s for next time', unzippedname)
            with open(unzippedpath, 'wb') as outfile:
                outfile.write(data)
            return data
    else:
        with open(filepath, 'rb') as infile:
            return infile.read()
def gen_partitions():
    """Generates the partition sequence.

    This uses the Pentagonal number theorem:

    > The identity implies a marvelous recurrence for calculating p(n), the number of partitions of n:
    > p(n) = p(n-1) + p(n-2) - p(n-5) - p(n-7) + ...
    >
    > [...] the series will eventually become zeroes, enabling discrete calculation.

    * The sign follows the pattern --++
    * The exponent coefficients are the generalized pentagonals

    - https://en.wikipedia.org/wiki/Partition_(number_theory)
    - https://en.wikipedia.org/wiki/Pentagonal_number_theorem
    - https://oeis.org/A000041
    """
    partitions = [1]
    signs = [1, 1, -1, -1]

    for n in count():
        partitions.append(0)

        pentagonals = takewhile(lambda penta: penta <= n,
                                gen_generalized_pentagonals())

        for sign, penta in zip(cycle(signs), pentagonals):
            partitions[n] += sign * partitions[n - penta]

        if (partitions[n] == 0):
            break

        info(f"p({n})={partitions[n]}")
        yield partitions[n]
def solve(limit):
    products = set()

    for a in range(1, limit):
        digits_a = unique_digits(a)
        if not digits_a:
            continue

        for b in range(a + 1, limit):
            digits_b = unique_digits(b)
            if not digits_b:
                continue

            p = a * b

            digits_p = unique_digits(p)
            if not digits_p:
                continue

            no_common_digits = digits_a.isdisjoint(digits_b)\
                and digits_b.isdisjoint(digits_p)\
                and digits_p.isdisjoint(digits_a)

            contains_all_digits = (digits_a | digits_b | digits_p) == DIGITS

            if no_common_digits and contains_all_digits:
                info(f"{a} * {b} = {p}")
                products.add(p)

    return sum(products)
Beispiel #7
0
def solve():
    result = 0
    limit = 50_000  # Found by trial and error

    for n in range(3, limit):
        if n == digit_factorial(n):
            info(f"%s = {n}", " + ".join(map(lambda d: d + "!", (str(n)))))
            result += n

    return result
Beispiel #8
0
def solve():
    limit = 10000
    p = list(islice(gen_pentagonal(), limit))
    ps = set(p)

    for j in range(1, limit):
        for k in range(j, limit):
            if p[k] - p[j] in ps and p[k] + p[j] in ps:
                info(
                    f"Pk={p[k]}, Pj={p[j]}, Pk-Pj={p[k]-p[j]}, Pk+Pj={p[k]+p[j]}"
                )
                return p[k] - p[j]
def solve(limit):
    max_primes = 0
    coefficients = ()

    for a, b in product(get_candidates(limit), repeat=2):
        primes = formula_primes(a, b)

        if len(primes) > max_primes:
            max_primes = len(primes)
            coefficients = (a, b)

    info(f"a={coefficients[0]}, b={coefficients[1]} yields {max_primes} primes")
    return prod(coefficients)
def solve(limit):
    divisor_sum = {}
    for n in range(limit):
        divisor_sum[n] = sum(proper_divisors(n))

    result = 0
    for a in range(1, limit):
        for b in range(a + 1, limit):
            if divisor_sum[a] == b and divisor_sum[b] == a:
                info(f"d({a}) = {b}\td({b}) = {a}")
                result += a + b

    return result
def solve(power, limit=100_000):
    """
    >>> solve(4)
    19316
    """
    result = 0

    for n in range(2, limit):
        if n == sum_of_digits_raised(n, power):
            info(f"{n} = %s", " + ".join(map(lambda d: f"{d}^{power}",
                                             str(n))))
            result += n

    return result
Beispiel #12
0
def solve(target):
    truncatable_primes = set()
    primes = dropwhile(lambda p: p in EXCLUDE, gen_primes())

    for p in primes:
        if len(truncatable_primes) == target:
            break

        truncations_p = truncations(p)
        if all(map(is_prime, truncations_p)):
            info(f"{p} = {truncations_p}")
            truncatable_primes.add(p)

    return sum(truncatable_primes)
def solve(limit):
    """Returns the numbers of circular primes below limit.

    >>> solve(100)
    13
    """
    primes = takewhile(lambda n: n < limit, gen_primes())
    count = 0

    for p in primes:
        if all(map(is_prime, rotations(p))):
            info(p)
            count += 1

    return count
Beispiel #14
0
def solve(limit):
    """
    >>> solve(150)
    """
    solutions = pythagorean_perimeters(limit)
    max_solutions = 0
    max_perimeter = 0

    for perimeter, solutions in solutions.items():
        if len(solutions) > max_solutions:
            info(f"p={perimeter}, {len(solutions)} solutions, {solutions}")
            max_perimeter = perimeter
            max_solutions = len(solutions)

    return max_perimeter
Beispiel #15
0
def solve(limit=7):
    d_min_x = {}

    for d in range(limit + 1):
        if square(d):
            continue

        x, y = pells_equation(d)
        d_min_x[d] = x

        info(f"D={d}, {x}^2 - {d}*{y}^2 = {(x*x) - (d*y*y)}")

    result = max(d_min_x, key=lambda k: d_min_x[k])
    info(f"D={result}, x={d_min_x[d]}")

    return result
Beispiel #16
0
def solve(target=91, limit=6):
    result_area, result_delta = 0, inf

    for h in range(1, limit):
        for w in range(1, limit):
            rectangles = triangle(h) * triangle(w)
            delta = abs(rectangles - target)
            area = h * w

            if delta < result_delta:
                result_area, result_delta = area, delta
                info(
                    f"{h}x{w}: rectangles={rectangles}, delta={delta}, area={area}"
                )

    return result_area
Beispiel #17
0
def solve():
    largest_pandigital = 0
    limit = 100_000
    scope = 999999999

    for x in range(1, limit):
        for up_to in range(1, 10):
            c = int(concatenated_product(x, up_to))

            if c > scope:
                break

            if is_pandigital(c) and c > largest_pandigital:
                info(f"{c}, n={up_to}")
                largest_pandigital = c

    return largest_pandigital
def solve():
    result = 1

    for n1 in range(1, 10):
        for d1 in range(n1 + 1, 10):
            for i in range(1, 10):

                n2 = n1 * 10 + i
                d2 = i * 10 + d1

                f1 = Fraction(n1, d1)
                f2 = Fraction(n2, d2)

                if f1 == f2:
                    info(f"{n2}/{d2} = {n1}/{d1}")
                    result *= f1

    return result.denominator
Beispiel #19
0
 def handle_connection(self) -> None:
     """Accept and handle a client connection"""
     try:
         # Accept the incoming connection
         self.client_sock, self.client_addr = self.server_sock.accept()
         logging.info('Client connected: {}', self.client_addr[0])
         while True:
             # Handle Pygame events and update the window
             self.handle_event(pygame.event.wait())
             self.window.update()
             # Receive and handle a message from the client, if one is available
             if recv_avail(self.client_sock):
                 message = recv_obj(self.client_sock, self.sock_timeout)
                 self.handle_message(message)
     except socket.error as err:
         logging.error('Client disconnected: {}', err)
     finally:
         self.client_sock.close()
         self.client_sock = None
         self.client_addr = None
Beispiel #20
0
def solve():
    digits = tuple(range(10))

    cubes = combinations(digits, 6)
    cubes = map(set, cubes)
    cubes = map(flippable, cubes)

    pairs = combinations(cubes, 2)

    result = 0

    for c1, c2 in pairs:
        for s1, s2 in SQUARES:
            if not ((s1 in c1 and s2 in c2) or (s2 in c1 and s1 in c2)):
                break
        else:
            result += 1
            info(f"{c1}, {c2}")

    return result
Beispiel #21
0
 def connect_and_run(self) -> None:
     """Connect to the server and run the client"""
     logging.info('Connecting to server: {}:{}', self.host, self.port)
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock.settimeout(self.SOCKET_TIMEOUT)
     try:
         self.sock.connect((self.host, self.port))
     except socket.error as err:
         logging.error('Unable to connect: {} (retrying in {}s)', err,
                       self.RECONNECT_DELAY)
         return
     logging.info("Connected to server")
     # Initialize a timer to periodically send a SystemInfoMessage
     send_system_info_timer = Timer(self.SYSTEM_INFO_INTERVAL,
                                    start_expired=True)
     try:
         # Inform the server of the current state of the Arduino connection
         send_obj(self.sock,
                  ArduinoConnectionMessage(self.arduino.is_connected()))
         while True:
             # Send a SystemInfoMessage if send_stats_interval has elapsed
             if send_system_info_timer.is_expired():
                 send_obj(self.sock, get_system_info_message())
                 send_system_info_timer.restart()
             # Receive and handle a command
             command = recv_obj(self.sock, self.SOCKET_TIMEOUT)
             self.handle_command(command)
     except socket.error as err:
         logging.error('Connection closed: {} (reconnecting in {}s)', err,
                       self.RECONNECT_DELAY)
     finally:
         self.sock.close()
         # If the Arduino is connected, try and stop the motors
         if self.arduino.is_connected():
             try:
                 self.arduino.write_speeds(None)
             except serial.SerialException:
                 pass
         # Stop the currently playing sound, if any
         self.sound_player.stop()
Beispiel #22
0
 def run(self) -> None:
     """Run the server"""
     try:
         # Create and bind the server socket
         self.server_sock = socket.socket(socket.AF_INET,
                                          socket.SOCK_STREAM)
         self.server_sock.settimeout(self.sock_timeout)
         self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
                                     1)
         self.server_sock.bind((self.host, self.port))
         self.server_sock.listen(1)
         logging.info('Server started on {}:{}', self.host or 'INADDR_ANY',
                      self.port)
         while True:
             # Handle Pygame events and update the window while waiting for an incoming connection
             while not recv_avail(self.server_sock):
                 self.handle_event(pygame.event.wait())
                 self.window.update()
             # Once an incoming connection is being made, handle it
             self.handle_connection()
     finally:
         self.server_sock.close()
Beispiel #23
0
def solve(limit):
    """
    >>> solve(6)
    30

    >>> solve(12)
    61
    """

    minimum = defaultdict(lambda: inf)
    queue = deque([(2, )])
    k2 = limit * 2

    while queue:
        numbers = queue.popleft()

        p = prod(numbers)
        s = sum(numbers)
        k = len(numbers) + (p - s)

        if p > k2:
            continue

        if k > 1 and k <= limit:
            minimum[k] = min(minimum[k], p)

        info(f"k={k}: {s} = {numbers}")

        left = numbers + (numbers[-1], )
        queue.append(left)

        right = numbers[:-1] + (numbers[-1] + 1, )
        queue.append(right)

    product_sums = set(minimum.values())
    info(product_sums)

    return sum(product_sums)
Beispiel #24
0
def solve(target):
    """
    >>> solve(2000)
    100
    """
    solutions = 0

    # Let the length be the bound M
    for length_m in count():
        for width_height in range(2 * length_m):
            path = sqrt(length_m**2 + width_height**2)

            if path.is_integer():
                folds = width_height // 2

                if width_height > length_m:
                    folds -= width_height - (length_m + 1)

                solutions += folds

        if solutions > target:
            info(f"Solutions: {solutions}")
            return length_m
def solve(limit=50):
    numbers = set()
    primes = list(takewhile(lambda p: p < sqrt(limit), gen_primes()))

    for a in primes:
        a2 = a**2

        for b in primes:
            b3 = b**3

            ab = a2 + b3

            for c in primes:
                c4 = c**4
                abc = ab + c4

                if abc >= limit:
                    break

                info(f"{abc} = {a}^2 + {b}^3 + {c}^4")
                numbers.add(abc)

    return len(numbers)
def solve(limit):
    total = 0

    n_1, n_2, sign = 1, 1, 1

    while True:
        # Calculate the next n given the 2 previous n
        n = n_1 * 4 - n_2 + 2 * sign

        sides = (n, n, n + sign * 1)
        perimeter = sum(sides)

        if perimeter > limit:
            break

        total += perimeter
        area = triangle_area(*sides)
        info(f"{sides}, area={area}, perimeter={perimeter}")

        # Move the previous n forward and flip the sign
        n_1, n_2 = n, n_1
        sign *= -1

    return total
Beispiel #27
0
def solve():
    data = read_data("p096_sudoku.txt")
    sudokus = parse_sudokus(data)
    result = 0

    for i, sudoku in enumerate(sudokus, 1):
        solved = solve_sudoku(sudoku)
        top_left = join_digits(sudoku[0][0:3])
        result += top_left

        info(f"Sudoku {i} {'solved' if solved else 'FAILED'}: {top_left}")
        info(sudoku)
        info("")

    return result
Beispiel #28
0
def colormap(force=False, view=False):
    '''
    return cached file or create a new one
    '''
    logging.info('colormap() called, force: %s, view: %s', force, view)
    init()
    print('content-type: text/json\r\n\r\n', end='')
    if os.path.exists(MAPFILE) and not force:
        logging.info('returning cached color map')
        with open(MAPFILE) as infile:
            colormap = infile.read()
    else:
        logging.info('creating new color map')
        colormap = json.dumps(create_colormap(view))
        with open(MAPFILE, 'w') as outfile:
            outfile.write(colormap)
    print(colormap, end='')
Beispiel #29
0
def pretty_info(ring):
    """Log the ring like in the problem description."""
    total = sum(ring[0])
    solution_set = '; '.join(map(lambda g: ','.join(map(str, g)), ring))

    info(f"{total}\t{solution_set}")
Beispiel #30
0
def launch_volcanojob(name, num_workers, image, working_dir, worker_command,
                      master_command):
    # 删除旧的volcanojob
    if KFJ_RUN_ID:
        logging.info('Try delete old volcanojob.')
    with HiddenPrints():
        try:
            k8s_client.delete_crd(group=crd_info['group'],
                                  version=crd_info['version'],
                                  plural=crd_info['plural'],
                                  namespace=KFJ_NAMESPACE,
                                  labels={"run-id": KFJ_RUN_ID})
            k8s_client.delete_crd(group=crd_info['group'],
                                  version=crd_info['version'],
                                  plural=crd_info['plural'],
                                  namespace=KFJ_NAMESPACE,
                                  name=name)
        except:
            logging.info('Nothing to delete, name:{}, run_id:{}'.format(
                name, KFJ_RUN_ID))
    time.sleep(10)

    # 创建新的volcanojob
    volcanojob_json = make_volcanojob(name=name,
                                      num_workers=num_workers,
                                      image=image,
                                      working_dir=working_dir,
                                      worker_command=worker_command,
                                      master_command=master_command)

    logging.info('Create new volcanojob %s' % name)
    logging.info(volcanojob_json)
    k8s_client.create_crd(group=crd_info['group'],
                          version=crd_info['version'],
                          plural=crd_info['plural'],
                          namespace=KFJ_NAMESPACE,
                          body=volcanojob_json)

    # 开子程程跟踪日志
    logging.info('Begin tracing logs')
    command = "sh stern.sh '{name}' '{namespace}'".format(
        name=name, namespace=KFJ_NAMESPACE)
    log_proc = subprocess.Popen(command,stdin=subprocess.PIPE, stderr=subprocess.PIPE, \
                            stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)

    # 阻塞到Volcanojob结束或者用户任务结束
    loop_time = 0
    while True:
        time.sleep(10)
        volcanojob = k8s_client.get_one_crd(group=crd_info['group'],
                                            version=crd_info['version'],
                                            plural=crd_info['plural'],
                                            namespace=KFJ_NAMESPACE,
                                            name=name)
        if not volcanojob:  # 获取volcanojob失败,再给一次机会
            time.sleep(10)
            volcanojob = k8s_client.get_one_crd(group=crd_info['group'],
                                                version=crd_info['version'],
                                                plural=crd_info['plural'],
                                                namespace=KFJ_NAMESPACE,
                                                name=name)

        line = nonBlockRead(log_proc.stdout)
        while line:
            logging.info(line.strip())
            line = nonBlockRead(log_proc.stdout)

        if loop_time % 60 == 0:
            logging.info("heartbeating, volcanojob status: {}".format(
                str(volcanojob['status'])))
        loop_time += 1

        if not volcanojob:
            break
        if volcanojob and (volcanojob['status'] not in ("Running", "Pending")):
            break

    if not volcanojob:
        raise RuntimeError  # ("Volcanojob disappear!!!Check if deleted artificial!!!")
    if volcanojob['status'] != 'Completed':
        logging.error("volcanojob %s finished, status %s" %
                      (name, volcanojob['status']))
        raise RuntimeError  # ("volcanojob %s finished, status %s"%(name, volcanojob['status']))
    logging.info("Volcanojob %s finished, status %s" %
                 (name, volcanojob['status']))