R

@RealSaitama

Happy Number

Python
1 year ago
# B4B solution from itertools import permutations from bisect import bisect PERMS = [int(''.join(p)) for p in permutations('0123456789') if p[0] != '0'] def next_happy_number(number): return PERMS[bisect(PERMS,number)] def _next_happy_number(n):

DLX

Python
1 year ago
#!/usr/bin/env python # # Copyright 2008 Sebastian Raaphorst. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #

Cover Problem (CodeWars)

Python
1 year ago
from collections import defaultdict def solve(X, Y, solution=[]): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r)

Finding Mr Wrong (SAT)

NodeJS
1 year ago
/* * sat.js * (C) 2012, all rights reserved, * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful,

Shortest Substring

Python
1 year ago
s = "BWABYXFYTTZDSGHYXEEZOOPXYZ" t = "XYYZ" from collections import Counter, defaultdict def shortest_substring(st, pat): n = len(st) cnt = Counter(pat) keys = cnt.keys() dct = defaultdict(int)

Permutation square root

Python
1 year ago
from collections import defaultdict def decompose(p): d = dict(enumerate(p)) ans = defaultdict(list) while d: x = list(d)[0] r = [] while x in d: r.append(x)

SAT solver

Python
1 year ago
from random import random, shuffle import re from functools import reduce from itertools import product class State: def __init__(self): self.empty = False self.vars = [None]

Sinkhorn

Python
1 year ago
import warnings import numpy as np class SinkhornKnopp: """ Sinkhorn Knopp Algorithm Takes a non-negative square matrix P, where P =/= 0

Optimal transport

Python
1 year ago
from functools import reduce class Pair: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"{self.x} {'+' if self.y >= 0 else '-'} {abs(self.y)}·ε"

Change Detection Decorator

Python
1 year ago
def change_detection(cls): class NonExistentAttribute(object): pass class JNoneMeta(type): def __subclasscheck__(currentCls, parentCls): return currentCls == JNone and parentCls == type(None) class JBoolMeta(type): def __subclasscheck__(currentCls, parentCls):

Imperfect Fibonacci Rabbits

Python
1 year ago
def fib(n, b, l): xs = [[1, 0]] for _ in range(n + 1): new_xs = [] ad = 0 for x, y in xs: if y < l: new_xs.append([x, y + 1]) for x, y in new_xs: if y > 1:

Simplex OT

Python
1 year ago
from functools import reduce def show(arr): return '\n'.join(' | '.join(str(x) for x in row) for row in arr) class Triplet: def __init__(self, x, y, z=0): self.x = x self.y = y self.z = z

Poney Express

Python
1 year ago
ds = [43, 23, 40, 13] idx = 4 "(0)----43----(1)----23----(2)----40----(3)----13----(4)" def solve(distances, missing_index): num_stations = len(distances) station_idx, rider_distance, num_riders = 0, 0, 1 done = False while station_idx < num_stations: if rider_distance + distances[station_idx] <= 100: if station_idx + 1 == missing_index - 1 and not done:

Package Visibility Puzzle

Python
1 year ago
s = "0;0 5;5 5;0 5;5 5;3 5;3 5;5 4;5 4;3 4;5 5;7 5;6 5;7 5;7" num = 3 def box_visible_directions(st, idx): n, m = 0, 0 for x in st.split(' '): y = x.split(';') j = int(y[0]) i = int(y[1]) n = max(n, i) m = max(m, j)

Sliding puzzle

Python
1 year ago
def make_dcts(arr): dct, target_dct = {}, {} n = len(arr) for i in range(n): for j in range(n): v = arr[i][j] dct[v] = (i, j) target_dct[v] = divmod(v - 1, n) if v > 0 else (n - 1, n - 1) return dct, target_dct

Wasserstein Distance

Python
1 year ago
import numpy as np u_values = [ 1, 2, 8, 9 ] v_values = [ 2, 4, 6, 8 ] u_weights = [ 0.375, 0.125, 0.125, 0.375 ] v_weights = [ 0.25, 0.25, 0.25, 0.25 ] def wasserstein(u, v, fu, fv): n, m = len(u), len(v)

Sparse Linear Algebra

Python
1 year ago
import heapq class SparseMatrixCSR: def __init__(self, data, indices, indptr, shape): self.data = data self.indices = indices self.indptr = indptr self.shape = shape def __repr__(self): f = f"Matrix of size {self.shape}"

symmlq

Python
1 year ago
import logging import numpy as np __docformat__ = 'restructuredtext' # Default (null) logger. null_log = logging.getLogger('krylov') null_log.setLevel(logging.INFO) null_log.addHandler(logging.NullHandler())

Sparse Gauss

Python
1 year ago
import numpy as np np.set_printoptions(suppress=True) def sparse_gauss(arr, n): h, k = 0, 0 while h < n and k < n + 1: idx, pivot = None, 0 for i in range(h, n):

Running C code (python)

Python
1 year ago
p = """cpdef matrix_sum(long n, long k): cdef long m = 1000000007 cdef long i = 1 cdef long p = n + k cdef long j = 1 for j in range(1, min([k+2, n])): i = (i * p * pow(j, -1, m)) % m p -= 1 return i """