Given an array containing only 0s, 1s, and 2s;
sort the array in ascending order.
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
test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2] ) test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertArrayEquals;- test.assert_equals(sort_values( [0,0,2,0,1,1,2,0]), [0,0,0,0,1,1,2,2] )
- test.assert_equals(sort_values([2, 0, 1, 2]), [0, 1, 2, 2])
// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {int[] inputArray = {0,0,2,0,1,1,2,0};int[] expectedArray = {0,0,0,0,1,1,2,2};assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));}@Testvoid testSomethingElse() {int[] inputArray = {2, 0, 1, 2};int[] expectedArray = {0, 1, 2, 2};assertArrayEquals(expectedArray, Kata.sortValues(inputArray, 8));}}
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)
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)
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
Test.assert_equals(return_hundred(),100)
Test.assertEquals(returnHundred(),100)- Test.assert_equals(return_hundred(),100)
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
import functools
Test.assert_equals(add_func(tuple)(range)(5), tuple(range(5)) )
@functools.lru_cache(None)
@add_func(list)
def vals(n):
for i in range(n):
yield n+i
Test.assert_equals(tuple(vals(5)), tuple(vals(5)) )
Test.assert_equals(vals(5), list(range(5,10)) )
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>25isPangram=s=>new Set(s.toLowerCase().match(/[a-z]/g)).size>25- def is_pangram(val:str):
- return set(val.lower()) >= set(string.ascii_lowercase)
Test.assert_equals(is_pangram('Quick zephyrs blow, vexing daft Jim'),True) Test.assert_equals(is_pangram('Sphinx of black quartz, judge my vow'),True) Test.assert_equals(is_pangram('Two driven jocks help fax my big quiz'),True) Test.assert_equals(is_pangram(' Five quacking zephyrs jolt my wax bed'),True) Test.assert_equals(is_pangram('A mad boxer shot a quick, gloved jab to the jaw of his dizzy opponent'),True) Test.assert_equals(is_pangram('Quick zephyrs blow, vexing daft '),False) Test.assert_equals(is_pangram('abcde'),False) Test.assert_equals(is_pangram(' Five quacking zephyrs jolt my wax bed143624131'),True)
describe("Solution", function() {it("should passed all test", function() {Test.assertEquals(isPangram('Quick zephyrs blow, vexing daft Jim'),true);Test.assertEquals(isPangram('Sphinx of black quartz, judge my vow'),true);Test.assertEquals(isPangram('Two driven jocks help fax my big quiz'),true);Test.assertEquals(isPangram(' Five quacking zephyrs jolt my wax bed'),true);Test.assertEquals(isPangram('A mad boxer shot a quick, gloved jab to the jaw of his dizzy opponent'),true);Test.assertEquals(isPangram('Quick zephyrs blow, vexing daft '),false);});});- Test.assert_equals(is_pangram('Quick zephyrs blow, vexing daft Jim'),True)
- Test.assert_equals(is_pangram('Sphinx of black quartz, judge my vow'),True)
- Test.assert_equals(is_pangram('Two driven jocks help fax my big quiz'),True)
- Test.assert_equals(is_pangram(' Five quacking zephyrs jolt my wax bed'),True)
- Test.assert_equals(is_pangram('A mad boxer shot a quick, gloved jab to the jaw of his dizzy opponent'),True)
- Test.assert_equals(is_pangram('Quick zephyrs blow, vexing daft '),False)
- Test.assert_equals(is_pangram('abcde'),False)
- Test.assert_equals(is_pangram(' Five quacking zephyrs jolt my wax bed143624131'),True)
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 = 0if "https://" in url:begin += 8elif "http://" in url:begin += 7if "www" in url:begin += 4return url[begin:].split(".")[0]- outers = [
- "https://",
- "http://",
- "www.",
- ]
- for prefix in outers:
- if url.startswith(prefix):
- url = url[len(prefix):]
- return url.split('.')[0]
Test.assert_equals(domain_name("http://google.com"), "google") Test.assert_equals(domain_name("http://google.co.jp"), "google") Test.assert_equals(domain_name("www.xakep.ru"), "xakep") Test.assert_equals(domain_name("https://youtube.com"), "youtube") Test.assert_equals(domain_name("https://fakewww.com"), "fakewww") Test.assert_equals(domain_name("https://wwwfakewww.com"), "wwwfakewww")
- Test.assert_equals(domain_name("http://google.com"), "google")
- Test.assert_equals(domain_name("http://google.co.jp"), "google")
- Test.assert_equals(domain_name("www.xakep.ru"), "xakep")
Test.assert_equals(domain_name("https://youtube.com"), "youtube")- Test.assert_equals(domain_name("https://youtube.com"), "youtube")
- Test.assert_equals(domain_name("https://fakewww.com"), "fakewww")
- Test.assert_equals(domain_name("https://wwwfakewww.com"), "wwwfakewww")
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 codepass- 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 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
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)
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