WeixiangYan/CodeTransOcean huggingface dataset:
Task: Gaussian primes







Python: 

from matplotlib.pyplot import scatter
from sympy import isprime
from math import isqrt

def norm(c):
    
    return c.real * c.real + c.imag * c.imag


def is_gaussian_prime(n):
    
    r, c = int(abs(n.real)), int(abs(n.imag))
    return isprime(r * r + c * c) or c == 0 and isprime(r) and (r - 3) % 4 == 0 or r == 0 and isprime(c) and (c - 3) % 4 == 0

if __name__ == '__main__':

    limitsquared = 100
    lim = isqrt(limitsquared)
    testvals = [complex(r, c) for r in range(-lim, lim) for c in range(-lim, lim)]
    gprimes = sorted(filter(lambda c : is_gaussian_prime(c) and norm(c) < limitsquared, testvals), key=norm)
    print(f'Gaussian primes within {isqrt(limitsquared)} of the origin on the complex plane:')
    for i, c in enumerate(gprimes):
        print(str(c).ljust(9), end='\n' if (i +1) % 10 == 0 else '')
    scatter([c.real for c in gprimes], [c.imag for c in gprimes])
Task: Doomsday rule







Python: from datetime import date
from calendar import isleap

def weekday(d):
    days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday"]
    dooms = [
        [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5],
        [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
    ]
    
    c = d.year // 100
    r = d.year % 100
    s = r // 12
    t = r % 12
    c_anchor = (5 * (c % 4) + 2) % 7
    doomsday = (s + t + (t // 4) + c_anchor) % 7
    anchorday = dooms[isleap(d.year)][d.month - 1]
    weekday = (doomsday + d.day - anchorday + 7) % 7
    return days[weekday]

dates = [date(*x) for x in
    [(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23),
     (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)]
]

for d in dates:
    tense = "was" if d < date.today() else "is" if d == date.today() else "will be"
    print("{} {} a {}".format(d.strftime("%B %d, %Y"), tense, weekday(d)))
Task: Gauss-Jordan matrix inversion







Python: import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)

print(a)
print(ainv)
Task: Numerical integration_Adaptive Simpson's method







Python: 



import math

import collections
triple = collections.namedtuple('triple', 'm fm simp')

def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
    
    m = a + (b - a) / 2
    fm = f(m)
    simp = abs(b - a) / 6 * (fa + 4*fm + fb)
    return triple(m, fm, simp,)
 
def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:
    
    lt = _quad_simpsons_mem(f, a, fa, m, fm)
    rt = _quad_simpsons_mem(f, m, fm, b, fb)
    delta = lt.simp + rt.simp - whole
    return (lt.simp + rt.simp + delta/15
        if (abs(delta) <= eps * 15) else
            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)
    )

def quad_asr(f: callable, a: float, b: float, eps: float)->float:
    
    fa = f(a)
    fb = f(b)
    t = _quad_simpsons_mem(f, a, fa, b, fb)
    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)

def main():
    (a, b,) = (0.0, 1.0,)
    sinx = quad_asr(math.sin, a, b, 1e-09);
    print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx))

main()
Task: Colorful numbers







Python: from math import prod

largest = [0]

def iscolorful(n):
    if 0 <= n < 10:
        return True
    dig = [int(c) for c in str(n)]
    if 1 in dig or 0 in dig or len(dig) > len(set(dig)):
        return False
    products = list(set(dig))
    for i in range(len(dig)):
        for j in range(i+2, len(dig)+1):
            p = prod(dig[i:j])
            if p in products:
                return False
            products.append(p)

    largest[0] = max(n, largest[0])
    return True

print('Colorful numbers for 1:25, 26:50, 51:75, and 76:100:')
for i in range(1, 101, 25):
    for j in range(25):
        if iscolorful(i + j):
            print(f'{i + j: 5,}', end='')
    print()

csum = 0
for i in range(8):
    j = 0 if i == 0 else 10**i
    k = 10**(i+1) - 1
    n = sum(iscolorful(x) for x in range(j, k+1))
    csum += n
    print(f'The count of colorful numbers between {j} and {k} is {n}.')

print(f'The largest possible colorful number is {largest[0]}.')
print(f'The total number of colorful numbers is {csum}.')
Task: Generate random chess position







Python: import random

board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]


def place_kings(brd):
	while True:
		rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
		diff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]
		if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
			brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
			break

def populate_board(brd, wp, bp):
	for x in range(2):
		if x == 0:
			piece_amount = wp
			pieces = piece_list
		else:
			piece_amount = bp
			pieces = [s.lower() for s in piece_list]
		while piece_amount != 0:
			piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
			piece = random.choice(pieces)
			if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
				brd[piece_rank][piece_file] = piece
				piece_amount -= 1

def fen_from_board(brd):
	fen = ""
	for x in brd:
		n = 0
		for y in x:
			if y == " ":
				n += 1
			else:
				if n != 0:
					fen += str(n)
				fen += y
				n = 0
		if n != 0:
			fen += str(n)
		fen += "/" if fen.count("/") < 7 else ""
	fen += " w - - 0 1\n"
	return fen

def pawn_on_promotion_square(pc, pr):
	if pc == "P" and pr == 0:
		return True
	elif pc == "p" and pr == 7:
		return True
	return False


def start():
	piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
	place_kings(board)
	populate_board(board, piece_amount_white, piece_amount_black)
	print(fen_from_board(board))
	for x in board:
		print(x)


start()
Task: Arithmetic derivative







Python: from sympy.ntheory import factorint

def D(n):
    if n < 0:
        return -D(-n)
    elif n < 2:
        return 0
    else:
        fdict = factorint(n)
        if len(fdict) == 1 and 1 in fdict: 
            return 1
        return sum([n * e // p for p, e in fdict.items()])

for n in range(-99, 101):
    print('{:5}'.format(D(n)), end='\n' if n % 10 == 0 else '')

print()
for m in range(1, 21):
    print('(D for 10**{}) divided by 7 is {}'.format(m, D(10 ** m) // 7))
Task: Special factorials







Python: 

from math import prod

def superFactorial(n):
    return prod([prod(range(1,i+1)) for i in range(1,n+1)])

def hyperFactorial(n):
    return prod([i**i for i in range(1,n+1)])

def alternatingFactorial(n):
    return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])

def exponentialFactorial(n):
    if n in [0,1]:
        return 1
    else:
        return n**exponentialFactorial(n-1)
        
def inverseFactorial(n):
    i = 1
    while True:
        if n == prod(range(1,i)):
            return i-1
        elif n < prod(range(1,i)):
            return "undefined"
        i+=1

print("Superfactorials for [0,9] :")
print({"sf(" + str(i) + ") " : superFactorial(i) for i in range(0,10)})

print("\nHyperfactorials for [0,9] :")
print({"H(" + str(i) + ") "  : hyperFactorial(i) for i in range(0,10)})

print("\nAlternating factorials for [0,9] :")
print({"af(" + str(i) + ") " : alternatingFactorial(i) for i in range(0,10)})

print("\nExponential factorials for [0,4] :")
print({str(i) + "$ " : exponentialFactorial(i) for i in range(0,5)})

print("\nDigits in 5$ : " , len(str(exponentialFactorial(5))))

factorialSet = [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]

print("\nInverse factorials for " , factorialSet)
print({"rf(" + str(i) + ") ":inverseFactorial(i) for i in factorialSet})

print("\nrf(119) : " + inverseFactorial(119))
Task: Sierpinski square curve







Python: import matplotlib.pyplot as plt
import math


def nextPoint(x, y, angle):
    a = math.pi * angle / 180
    x2 = (int)(round(x + (1 * math.cos(a))))
    y2 = (int)(round(y + (1 * math.sin(a))))
    return x2, y2


def expand(axiom, rules, level):
    for l in range(0, level):
        a2 = ""
        for c in axiom:
            if c in rules:
                a2 += rules[c]
            else:
                a2 += c
        axiom = a2
    return axiom


def draw_lsystem(axiom, rules, angle, iterations):
    xp = [1]
    yp = [1]
    direction = 0
    for c in expand(axiom, rules, iterations):
        if c == "F":
            xn, yn = nextPoint(xp[-1], yp[-1], direction)
            xp.append(xn)
            yp.append(yn)
        elif c == "-":
            direction = direction - angle
            if direction < 0:
                direction = 360 + direction
        elif c == "+":
            direction = (direction + angle) % 360

    plt.plot(xp, yp)
    plt.show()


if __name__ == '__main__':
    
    s_axiom = "F+XF+F+XF"
    s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
    s_angle = 90

    draw_lsystem(s_axiom, s_rules, s_angle, 3)
Task: Achilles numbers







Python: from math import gcd
from sympy import factorint
 
def is_Achilles(n):
    p = factorint(n).values()
    return all(i > 1 for i in p) and gcd(*p) == 1

def is_strong_Achilles(n):
    return is_Achilles(n) and is_Achilles(totient(n))
 
def test_strong_Achilles(nachilles, nstrongachilles):
    
    print('First', nachilles, 'Achilles numbers:')
    n, found = 0, 0
    while found < nachilles:
        if is_Achilles(n):
            found += 1
            print(f'{n: 8,}', end='\n' if found % 10 == 0 else '')
        n += 1

    
    print('\nFirst', nstrongachilles, 'strong Achilles numbers:')
    n, found = 0, 0
    while found < nstrongachilles:
        if is_strong_Achilles(n):
            found += 1
            print(f'{n: 9,}', end='\n' if found % 10 == 0 else '')
        n += 1

    
    print('\nCount of Achilles numbers for various intervals:')
    intervals = [[10, 99], [100, 999], [1000, 9999], [10000, 99999], [100000, 999999]]
    for interval in intervals:
        print(f'{interval}:', sum(is_Achilles(i) for i in range(*interval)))


test_strong_Achilles(50, 100)
Task: Permutations with some identical elements







Python: 

from itertools import permutations

numList = [2,3,1]

baseList = []

for i in numList:
    for j in range(0,i):
        baseList.append(i)

stringDict = {'A':2,'B':3,'C':1}

baseString=""

for i in stringDict:
    for j in range(0,stringDict[i]):
        baseString+=i

print("Permutations for " + str(baseList) + " : ")
[print(i) for i in set(permutations(baseList))]

print("Permutations for " + baseString + " : ")
[print(i) for i in set(permutations(baseString))]
Task: Pisano period







Python: from sympy import isprime, lcm, factorint, primerange
from functools import reduce


def pisano1(m):
    "Simple definition"
    if m < 2:
        return 1
    lastn, n = 0, 1
    for i in range(m ** 2):
        lastn, n = n, (lastn + n) % m
        if lastn == 0 and n == 1:
            return i + 1
    return 1

def pisanoprime(p, k):
    "Use conjecture π(p ** k) == p ** (k − 1) * π(p) for prime p and int k > 1"
    assert isprime(p) and k > 0
    return p ** (k - 1) * pisano1(p)

def pisano_mult(m, n):
    "pisano(m*n) where m and n assumed coprime integers"
    return lcm(pisano1(m), pisano1(n))

def pisano2(m):
    "Uses prime factorization of m"
    return reduce(lcm, (pisanoprime(prime, mult)
                        for prime, mult in factorint(m).items()), 1)


if __name__ == '__main__':
    for n in range(1, 181):
        assert pisano1(n) == pisano2(n), "Wall-Sun-Sun prime exists??!!"
    print("\nPisano period (p, 2) for primes less than 50\n ",
          [pisanoprime(prime, 2) for prime in primerange(1, 50)])
    print("\nPisano period (p, 1) for primes less than 180\n ",
          [pisanoprime(prime, 1) for prime in primerange(1, 180)])
    print("\nPisano period (p) for integers 1 to 180")
    for i in range(1, 181):
        print(" %3d" % pisano2(i), end="" if i % 10 else "\n")
Task: Numerical and alphabetical suffixes







Python: from functools import reduce
from operator import mul
from decimal import *

getcontext().prec = MAX_PREC

def expand(num):
    suffixes = [
        
        ('greatgross', 7, 12, 3),
        ('gross', 2, 12, 2),
        ('dozens', 3, 12, 1),
        ('pairs', 4, 2, 1),
        ('scores', 3, 20, 1),
        ('googols', 6, 10, 100),
        ('ki', 2, 2, 10),
        ('mi', 2, 2, 20),
        ('gi', 2, 2, 30),
        ('ti', 2, 2, 40),
        ('pi', 2, 2, 50),
        ('ei', 2, 2, 60),
        ('zi', 2, 2, 70),
        ('yi', 2, 2, 80),
        ('xi', 2, 2, 90),
        ('wi', 2, 2, 100),
        ('vi', 2, 2, 110),
        ('ui', 2, 2, 120),
        ('k', 1, 10, 3),
        ('m', 1, 10, 6),
        ('g', 1, 10, 9),
        ('t', 1, 10, 12),
        ('p', 1, 10, 15),
        ('e', 1, 10, 18),
        ('z', 1, 10, 21),
        ('y', 1, 10, 24),
        ('x', 1, 10, 27),
        ('w', 1, 10, 30)
    ]

    num = num.replace(',', '').strip().lower()

    if num[-1].isdigit():
        return float(num)

    for i, char in enumerate(reversed(num)):
        if char.isdigit():
            input_suffix = num[-i:]
            num = Decimal(num[:-i])
            break

    if input_suffix[0] == '!':
        return reduce(mul, range(int(num), 0, -len(input_suffix)))

    while len(input_suffix) > 0:
        for suffix, min_abbrev, base, power in suffixes:
            if input_suffix[:min_abbrev] == suffix[:min_abbrev]:
                for i in range(min_abbrev, len(input_suffix) + 1):
                    if input_suffix[:i+1] != suffix[:i+1]:
                        num *= base ** power
                        input_suffix = input_suffix[i:]
                        break
                break

    return num


test = "2greatGRo   24Gros  288Doz  1,728pairs  172.8SCOre\n\
        1,567      +1.567k    0.1567e-2m\n\
        25.123kK    25.123m   2.5123e-00002G\n\
        25.123kiKI  25.123Mi  2.5123e-00002Gi  +.25123E-7Ei\n\
        -.25123e-34Vikki      2e-77gooGols\n\
        9!   9!!   9!!!   9!!!!   9!!!!!   9!!!!!!   9!!!!!!!   9!!!!!!!!   9!!!!!!!!!"

for test_line in test.split("\n"):
    test_cases = test_line.split()
    print("Input:", ' '.join(test_cases))
    print("Output:", ' '.join(format(result, ',f').strip('0').strip('.') for result in map(expand, test_cases)))
Task: Minkowski question-mark function







Python:     print(
        "{:19.16f} {:19.16f}".format(
            minkowski(minkowski_inv(4.04145188432738056)),
            minkowski_inv(minkowski(4.04145188432738056)),
        )
    )
Task: Dating agency







Python: 

sailors = ['Adrian', 'Caspian', 'Dune', 'Finn', 'Fisher', 'Heron', 'Kai',
           'Ray', 'Sailor', 'Tao']

ladies = ['Ariel', 'Bertha', 'Blue', 'Cali', 'Catalina', 'Gale', 'Hannah',
           'Isla', 'Marina', 'Shelly']

def isnicegirl(s):
    return ord(s[0]) % 2 == 0

def islovable(slady, ssailor):
    return ord(slady[-1]) % 2 == ord(ssailor[-1]) % 2

for lady in ladies:
    if isnicegirl(lady):
        print("Dating service should offer a date with", lady)
        for sailor in sailors:
            if islovable(lady, sailor):
                print("    Sailor", sailor, "should take an offer to date her.")
    else:
        print("Dating service should NOT offer a date with", lady)
Task: Compiler_AST interpreter







Python: def load_ast()
    line = readline()
    
    line_list = tokenize the line, respecting double quotes

    text = line_list[0] 

    if text == ";"   
        return NULL

    node_type = text 

    
    
    
    if len(line_list) > 1
        return make_leaf(node_type, line_list[1])

    left = load_ast()
    right = load_ast()
    return make_node(node_type, left, right)
Task: Welch's t-test







Python: import numpy as np
import scipy as sp
import scipy.stats

def welch_ttest(x1, x2):
    n1 = x1.size
    n2 = x2.size
    m1 = np.mean(x1)
    m2 = np.mean(x2)
    v1 = np.var(x1, ddof=1)
    v2 = np.var(x2, ddof=1)
    t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
    df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - 1)) + v2**2 / (n2**2 * (n2 - 1)))
    p = 2 * sp.stats.t.cdf(-abs(t), df)
    return t, df, p

welch_ttest(np.array([3.0, 4.0, 1.0, 2.1]), np.array([490.2, 340.0, 433.9]))
(-9.559497721932658, 2.0008523488562844, 0.01075156114978449)
Task: Mayan calendar







Python: import datetime


def g2m(date, gtm_correlation=True):
    

    

    correlation = 584283 if gtm_correlation else 584285

    long_count_days = [144000, 7200, 360, 20, 1]

    tzolkin_months = ['Imix’', 'Ik’', 'Ak’bal', 'K’an', 'Chikchan', 'Kimi', 'Manik’', 'Lamat', 'Muluk', 'Ok', 'Chuwen',
                      'Eb', 'Ben', 'Hix', 'Men', 'K’ib’', 'Kaban', 'Etz’nab’', 'Kawak', 'Ajaw']  

    haad_months = ['Pop', 'Wo’', 'Sip', 'Sotz’', 'Sek', 'Xul', 'Yaxk’in', 'Mol', 'Ch’en', 'Yax', 'Sak’', 'Keh', 'Mak',
                   'K’ank’in', 'Muwan', 'Pax', 'K’ayab', 'Kumk’u', 'Wayeb’']  

    gregorian_days = datetime.datetime.strptime(date, '%Y-%m-%d').toordinal()
    julian_days = gregorian_days + 1721425

    

    long_date = list()
    remainder = julian_days - correlation

    for days in long_count_days:

        result, remainder = divmod(remainder, days)
        long_date.append(int(result))

    long_date = '.'.join(['{:02d}'.format(d) for d in long_date])

    

    tzolkin_month = (julian_days + 16) % 20
    tzolkin_day = ((julian_days + 5) % 13) + 1

    haab_month = int(((julian_days + 65) % 365) / 20)
    haab_day = ((julian_days + 65) % 365) % 20
    haab_day = haab_day if haab_day else 'Chum'

    lord_number = (julian_days - correlation) % 9
    lord_number = lord_number if lord_number else 9

    round_date = f'{tzolkin_day} {tzolkin_months[tzolkin_month]} {haab_day} {haad_months[haab_month]} G{lord_number}'

    return long_date, round_date

if __name__ == '__main__':

    dates = ['2004-06-19', '2012-12-18', '2012-12-21', '2019-01-19', '2019-03-27', '2020-02-29', '2020-03-01']

    for date in dates:

        long, round = g2m(date)
        print(date, long, round)
Task: Four is the number of letters in the ...







Python: 




import inflect

def count_letters(word):
    
    count = 0
    for letter in word:
        if letter != ',' and letter !='-' and letter !=' ':
            count += 1
            
    return count
    
def split_with_spaces(sentence):
    
    sentence_list = []
    curr_word = ""
    for c in sentence:
        if c == " " and curr_word != "":
            
            
            sentence_list.append(curr_word+" ")
            curr_word = ""
        else:
            curr_word += c
    
    
    
    if len(curr_word) > 0:
        sentence_list.append(curr_word)
    
    return sentence_list
    
def my_num_to_words(p, my_number):
    
    
    number_string_list = p.number_to_words(my_number, wantlist=True, andword='')
    
    number_string = number_string_list[0]
    
    for i in range(1,len(number_string_list)):
        number_string += " " + number_string_list[i]
    
    return number_string
        
def build_sentence(p, max_words):
    
    
    
    
    sentence_list = split_with_spaces("Four is the number of letters in the first word of this sentence,")
      
    num_words = 13
    
    
    
    
    word_number = 2
    
    
    
    while num_words < max_words:
        
        
        
        
        
        ordinal_string = my_num_to_words(p, p.ordinal(word_number))
        
        
        
        word_number_string = my_num_to_words(p, count_letters(sentence_list[word_number - 1]))
        
        
        
        new_string = " "+word_number_string+" in the "+ordinal_string+","

        new_list = split_with_spaces(new_string)
        
        sentence_list += new_list

        
        
        num_words += len(new_list)
        
        
        
        word_number += 1
        
    return sentence_list, num_words
    
def word_and_counts(word_num):
    
        
    sentence_list, num_words = build_sentence(p, word_num)
    
    word_str = sentence_list[word_num - 1].strip(' ,')
    
    num_letters = len(word_str)
    
    num_characters = 0
    
    for word in sentence_list:
       num_characters += len(word)
       
    print('Word {0:8d} is "{1}", with {2} letters.  Length of the sentence so far: {3}  '.format(word_num,word_str,num_letters,num_characters))
   
    
p = inflect.engine()

sentence_list, num_words = build_sentence(p, 201)

print(" ")
print("The lengths of the first 201 words are:")
print(" ")

print('{0:3d}:  '.format(1),end='')

total_characters = 0

for word_index in range(201):

    word_length = count_letters(sentence_list[word_index])
    
    total_characters += len(sentence_list[word_index])
    
    print('{0:2d}'.format(word_length),end='')
    if (word_index+1) % 20 == 0:
        
        print(" ")
        print('{0:3d}:  '.format(word_index + 2),end='')
    else:
        print(" ",end='')
 
print(" ")
print(" ")
print("Length of the sentence so far: "+str(total_characters))
print(" ")



word_and_counts(1000)
word_and_counts(10000)
word_and_counts(100000)
word_and_counts(1000000)
word_and_counts(10000000)
Task: Wordle comparison







Python: 

from functools import reduce
from operator import add



def wordleScore(target, guess):
    
    return mapAccumL(amber)(
        *first(charCounts)(
            mapAccumL(green)(
                [], zip(target, guess)
            )
        )
    )[1]



def green(residue, tg):
    
    t, g = tg
    return (residue, (g, 2)) if t == g else (
        [t] + residue, (g, 0)
    )



def amber(tally, cn):
    
    c, n = cn
    return (tally, 2) if 2 == n else (
        adjust(
            lambda x: x - 1,
            c, tally
        ),
        1
    ) if 0 < tally.get(c, 0) else (tally, 0)




def main():
    
    print(' -> '.join(['Target', 'Guess', 'Scores']))
    print()
    print(
        '\n'.join([
            wordleReport(*tg) for tg in [
                ("ALLOW", "LOLLY"),
                ("CHANT", "LATTE"),
                ("ROBIN", "ALERT"),
                ("ROBIN", "SONIC"),
                ("ROBIN", "ROBIN"),
                ("BULLY", "LOLLY"),
                ("ADAPT", "SÅLÅD"),
                ("Ukraine", "Ukraíne"),
                ("BBAAB", "BBBBBAA"),
                ("BBAABBB", "AABBBAA")
            ]
        ])
    )



def wordleReport(target, guess):
    
    scoreName = {2: 'green', 1: 'amber', 0: 'gray'}

    if 5 != len(target):
        return f'{target}: Expected 5 character target.'
    elif 5 != len(guess):
        return f'{guess}: Expected 5 character guess.'
    else:
        scores = wordleScore(target, guess)
        return ' -> '.join([
            target, guess, repr(scores),
            ' '.join([
                scoreName[n] for n in scores
            ])
        ])





def adjust(f, k, dct):
    
    return dict(
        dct,
        **{k: f(dct[k]) if k in dct else None}
    )



def charCounts(s):
    
    return reduce(
        lambda a, c: insertWith(add)(c)(1)(a),
        list(s),
        {}
    )



def first(f):
    
    return lambda xy: (f(xy[0]), xy[1])




def insertWith(f):
    
    return lambda k: lambda x: lambda dct: dict(
        dct,
        **{k: f(dct[k], x) if k in dct else x}
    )




def mapAccumL(f):
    
    def nxt(a, x):
        return second(lambda v: a[1] + [v])(
            f(a[0], x)
        )
    return lambda acc, xs: reduce(
        nxt, xs, (acc, [])
    )



def second(f):
    
    return lambda xy: (xy[0], f(xy[1]))



if __name__ == '__main__':
    main()