Ad

Given an array containing only 0s, 1s, and 2s;
sort the array in ascending order.

Code
Diff
  • from __future__ import annotations
    from collections import Counter
    
    def sort_values(vals:list[int]) -> list[int]:
        #Given an array of size N containing only 0s, 1s, and 2s; 
        #sort the array in ascending order.
        assert set(vals) <= {0,1,2}
        return counting_sort(vals)
        # O(n+k) instead of n log(n)
    
    def counting_sort(vals:list[T]) -> list[T]:
        res = []
        c = Counter(vals)
        for k,amt in sorted(c.items()):
            res += [k]*amt
        return res
    • import java.util.Arrays;
    • public class Kata {
    • public static int[] sortValues(int[] my_array, int size) {
    • // Given an array of size N containing only 0s, 1s, and 2s;
    • // sort the array in ascending order.
    • Arrays.sort(my_array);
    • return my_array;
    • }
    • }
    • from __future__ import annotations
    • from collections import Counter
    • def sort_values(vals:list[int]) -> list[int]:
    • #Given an array of size N containing only 0s, 1s, and 2s;
    • #sort the array in ascending order.
    • assert set(vals) <= {0,1,2}
    • return counting_sort(vals)
    • # O(n+k) instead of n log(n)
    • def counting_sort(vals:list[T]) -> list[T]:
    • res = []
    • c = Counter(vals)
    • for k,amt in sorted(c.items()):
    • res += [k]*amt
    • return res
Code
Diff
  • def sum_digits_of(n:int) -> int:
        return sum(map(int, str(n)))
    
    
    SumDigitsOf = sum_digits_of
    • def SumDigitsOf(integer):
    • return sum([int(value) for value in str(integer)])
    • def sum_digits_of(n:int) -> int:
    • return sum(map(int, str(n)))
    • SumDigitsOf = sum_digits_of
Code
Diff
  • def digit_sum(n: int) -> int:
        return sum(map(int, str(abs(n))))
    
    • def digit_sum(number: int) -> int:
    • return(sum([int(num) for num in str(abs(number))]))
    • def digit_sum(n: int) -> int:
    • return sum(map(int, str(abs(n))))
Code
Diff
  • import itertools
    
    def return_hundred():
        return p(p(0)+p(0))*p(p(p(0)) - p(0)) + p(p(0))*(p(p(0)) - p(0)) + p(0)**(p(p(0)) - p(0))
    
    def p(n):
        """n'th prime"""
        pr = primes()
        for _ in range(n): next(pr) # consume n-1 values
        return next(pr)
    
    def primes():
        seen = set()
        for n in itertools.count(start=2):
            if not any((n % p ==0)for p in seen ):
                yield n
                seen.add(n)
                
    • def return_hundred():
    • return globals()[__import__('inspect').stack()[0][3][6]]
    • import itertools
    • def return_hundred():
    • return p(p(0)+p(0))*p(p(p(0)) - p(0)) + p(p(0))*(p(p(0)) - p(0)) + p(0)**(p(p(0)) - p(0))
    • _= 100
    • def p(n):
    • """n'th prime"""
    • pr = primes()
    • for _ in range(n): next(pr) # consume n-1 values
    • return next(pr)
    • def primes():
    • seen = set()
    • for n in itertools.count(start=2):
    • if not any((n % p ==0)for p in seen ):
    • yield n
    • seen.add(n)

using e, pi, +, -, /, **, (, ), (and round)

Code
Diff
  • import math
    
    def hundred():
        pi = math.pi
        e = math.e
        val = pi**(pi + e/pi + pi**-pi) - pi/e - e**-e - e**-e - pi**-pi + pi**-(pi+pi/e) + pi**-(pi+e) - pi**-(pi+pi+e/pi)
        # 100.00000349005191
        return round(val)
    • import math
    • def hundred():
    • golden = ((1 + 5 ** 0.5)/2)
    • return round((math.pi * math.e) ** golden * math.sqrt(math.pi * math.e) + math.pi * golden + golden / math.e + golden / (math.pi ** golden))
    • pi = math.pi
    • e = math.e
    • val = pi**(pi + e/pi + pi**-pi) - pi/e - e**-e - e**-e - pi**-pi + pi**-(pi+pi/e) + pi**-(pi+e) - pi**-(pi+pi+e/pi)
    • # 100.00000349005191
    • return round(val)
Code
Diff
  • import math
    def  return_hundred(): 
        return (math.log( 2**3 * 37 * ((5 * 11 * (2**10-5) * 2**15 * 3**4) + 7))/math.pi )**2
        
    # with help from wolframalpha
    • const returnHundred = () => 228 & 127;
    • // based on the rule that a & (2**b - 1) = a % 2**b
    • import math
    • def return_hundred():
    • return (math.log( 2**3 * 37 * ((5 * 11 * (2**10-5) * 2**15 * 3**4) + 7))/math.pi )**2
    • # with help from wolframalpha

create a function (0) that takes a function_ (1) and returns a decorator (2) that calls function_ (1) on the output of the func (3) the decorator (2) reads.

Okay, that was confusing. We want to be able to apply a func to the output of another func, in a way that affects the func (e.g. it might be easiest to write a func using yield, but that causes issues if you want to memoize it and reuse the output)

def add_func(operator):
    def inner(func):
        def thingy(*args, **kwargs):
            return operator( func(*args, **kwargs))
        return thingy
    return inner
Arrays
Data Types
Regular Expressions
Declarative Programming
Advanced Language Features
Programming Paradigms
Fundamentals
Strings
Code
Diff
  • import string
    
    def is_pangram(val:str):
        return set(val.lower()) >= set(string.ascii_lowercase)
    • // some other ways
    • import string
    • isPangram=s=>[...'abcdefghijklmnopqrstuvwxyz'].every(e=>s.toLowerCase().includes(e))
    • isPangram=s=>[...'abcdefghijklmnopqrstuvwxyz'].every(e=>RegExp(e,'i').test(s))
    • isPangram=s=>[...new Set(s.toLowerCase().match(/[a-z]/g))].length>25
    • isPangram=s=>new Set(s.toLowerCase().match(/[a-z]/g)).size>25
    • def is_pangram(val:str):
    • return set(val.lower()) >= set(string.ascii_lowercase)
Code
Diff
  • def domain_name(url):
        outers = [
            "https://",
            "http://",
            "www.",
        ]
        for prefix in outers:
            if url.startswith(prefix):
                url =  url[len(prefix):]
     
        return url.split('.')[0]
    • def domain_name(url):
    • begin = 0
    • if "https://" in url:
    • begin += 8
    • elif "http://" in url:
    • begin += 7
    • if "www" in url:
    • begin += 4
    • return url[begin:].split(".")[0]
    • outers = [
    • "https://",
    • "http://",
    • "www.",
    • ]
    • for prefix in outers:
    • if url.startswith(prefix):
    • url = url[len(prefix):]
    • return url.split('.')[0]
Algebra
Mathematics
Algorithms
Logic
Code
Diff
  • def multiply(a, b):
        a,b = list(map(digits, [a,b]))
        res = [0 for _ in range(len(a+b)-1)]
        for i,n in enumerate(a):
            for j,m in enumerate(b):
                res[i+j] += n*m
        return res
        
    def digits(n):
        return list(map(int, str(n)))
        
    
    • def multiply(a, b):
    • #your code
    • pass
    • a,b = list(map(digits, [a,b]))
    • res = [0 for _ in range(len(a+b)-1)]
    • for i,n in enumerate(a):
    • for j,m in enumerate(b):
    • res[i+j] += n*m
    • return res
    • def digits(n):
    • return list(map(int, str(n)))
Numbers
Data Types
Fundamentals
Code
Diff
  • def perfect(numbers):
        #Code goes here. Good Luck!
        
        return list(filter(is_square, numbers))
        
    def is_square(n):
        return round( n**.5 )**2 == n
    • def perfect(numbers):
    • #Code goes here. Good Luck!
    • return [i for i in numbers if i == (i ** 0.5) ** 2]
    • return list(filter(is_square, numbers))
    • def is_square(n):
    • return round( n**.5 )**2 == n
Code
Diff
  • def field_to_coordinate(field):
        x,y = field[0], field[1:]
        return (ord(x) - 97, int(y) - 1)
    • import re
    • def field_to_coordinate(field):
    • # Compute a coordinate which represents specified `field`,
    • # i.e. if field = 'd2' returned value should be [3, 1]
    • x, y = re.search(r"([^\d])(\d+)", field).groups()
    • x,y = field[0], field[1:]
    • return (ord(x) - 97, int(y) - 1)
Mathematics
Algorithms
Logic
Numbers
Fundamentals
Data Types
Code
Diff
  • def compute(n):
    	return total(n,3) + total(n,5) - total(n,3*5)
        
    def total(n, k):
        r = (n-1)//k
        return tri(r) * k
        
    def tri(n):
        return (n*(n+1))//2
    • def compute(n):
    • return sum(x for x in range(n) if (x % 3 == 0 or x % 5 == 0))
    • return total(n,3) + total(n,5) - total(n,3*5)
    • def total(n, k):
    • r = (n-1)//k
    • return tri(r) * k
    • def tri(n):
    • return (n*(n+1))//2