WeixiangYan/CodeTransOcean huggingface dataset:
Task: Peaceful chess queen armies







Python: from itertools import combinations, product, count
from functools import lru_cache, reduce


_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__

def place(m, n):
    "Place m black and white queens, peacefully, on an n-by-n board"
    board = set(product(range(n), repeat=2))  
    placements = {frozenset(c) for c in combinations(board, m)}
    for blacks in placements:
        black_attacks = reduce(_or, 
                               (queen_attacks_from(pos, n) for pos in blacks), 
                               set())
        for whites in {frozenset(c)     
                       for c in combinations(board - black_attacks, m)}:
            if not black_attacks & whites:
                return blacks, whites
    return set(), set()

@lru_cache(maxsize=None)
def queen_attacks_from(pos, n):
    x0, y0 = pos
    a = set([pos])    
    a.update((x, y0) for x in range(n))    
    a.update((x0, y) for y in range(n))    
    
    for x1 in range(n):
        
        y1 = y0 -x0 +x1
        if 0 <= y1 < n: 
            a.add((x1, y1))
        
        y1 = y0 +x0 -x1
        if 0 <= y1 < n: 
            a.add((x1, y1))
    return a

def pboard(black_white, n):
    "Print board"
    if black_white is None: 
        blk, wht = set(), set()
    else:
        blk, wht = black_white
    print(f"
          f"on a {n}-by-{n} board:", end='')
    for x, y in product(range(n), repeat=2):
        if y == 0:
            print()
        xy = (x, y)
        ch = ('?' if xy in blk and xy in wht 
              else 'B' if xy in blk
              else 'W' if xy in wht
              else _bbullet if (x + y)%2 else _wbullet)
        print('%s' % ch, end='')
    print()

if __name__ == '__main__':
    n=2
    for n in range(2, 7):
        print()
        for m in count(1):
            ans = place(m, n)
            if ans[0]:
                pboard(ans, n)
            else:
                print (f"
                break
    
    print('\n')
    m, n = 5, 7
    ans = place(m, n)
    pboard(ans, n)
Task: Sequence_ nth number with exactly n divisors







Python: def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))


def is_prime(n):
    return len(divisors(n)) == 2


def primes():
    ii = 1
    while True:
        ii += 1
        if is_prime(ii):
            yield ii


def prime(n):
    generator = primes()
    for ii in range(n - 1):
        generator.__next__()
    return generator.__next__()


def n_divisors(n):
    ii = 0
    while True:
        ii += 1
        if len(divisors(ii)) == n:
            yield ii


def sequence(max_n=None):
    if max_n is not None:
        for ii in range(1, max_n + 1):
            if is_prime(ii):
                yield prime(ii) ** (ii - 1)
            else:
                generator = n_divisors(ii)
                for jj, out in zip(range(ii - 1), generator):
                    pass
                yield generator.__next__()
    else:
        ii = 1
        while True:
            ii += 1
            if is_prime(ii):
                yield prime(ii) ** (ii - 1)
            else:
                generator = n_divisors(ii)
                for jj, out in zip(range(ii - 1), generator):
                    pass
                yield generator.__next__()


if __name__ == '__main__':
    for item in sequence(15):
        print(item)
Task: Readline interface







Python: 






import readline

while True:
    try:
        print(input('> '))
    except:
        break
Task: Just in time processing on a character stream







Python: import sys

class UserInput:
    def __init__(self,chunk):
        self.formFeed = int(chunk[0])
        self.lineFeed = int(chunk[1])
        self.tab = int(chunk[2])
        self.space = int(chunk[3])

    def __str__(self):
        return "(ff=%d; lf=%d; tb=%d; sp%d)" % (self.formFeed,self.lineFeed,self.tab,self.space)

def chunks(l,n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

def getUserInput():
    h = "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 "\
        "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47 0 84 2 28"
    ha = h.split()
    return [UserInput(chunk) for chunk in chunks(ha, 4)]

def decode(filename,uiList):
    f = open(filename, "r")
    text = f.read()

    def decode2(ui):
        f = 0
        l = 0
        t = 0
        s = 0
        for c in text:
            if f == ui.formFeed and l == ui.lineFeed and t == ui.tab and s == ui.space:
                if c == '!':
                    return False
                sys.stdout.write(c)
                return True
            if c == '\u000c':
                f=f+1
                l=0
                t=0
                s=0
            elif c == '\n':
                l=l+1
                t=0
                s=0
            elif c == '\t':
                t=t+1
                s=0
            else:
                s=s+1
        return False

    for ui in uiList:
        if not decode2(ui):
            break
    print



uiList = getUserInput()
decode("theRaven.txt", uiList)
Task: Print debugging statement







Python: import logging, logging.handlers

LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG


def print_squares(number):
    logger.info("In print_squares")
    for i in range(number):
        print("square of {0} is {1}".format(i , i*i))
        logger.debug(f'square of {i} is {i*i}')

def print_cubes(number):
    logger.info("In print_cubes")
    for j in range(number):
        print("cube of {0} is {1}".format(j, j*j*j))
        logger.debug(f'cube of {j} is {j*j*j}')

if __name__ == "__main__":

    logger = logging.getLogger("logdemo")
    logger.setLevel(LOGLEVEL)
    handler = logging.FileHandler(LOG_FILENAME)
    handler.setFormatter(logging.Formatter(FORMAT_STRING))
    logger.addHandler(handler)

    print_squares(10)
    print_cubes(10)

    logger.info("All done")
Task: Montgomery reduction







Python: class Montgomery:
    BASE = 2

    def __init__(self, m):
        self.m = m
        self.n = m.bit_length()
        self.rrm = (1 << (self.n * 2)) % m

    def reduce(self, t):
        a = t
        for i in xrange(self.n):
            if (a & 1) == 1:
                a = a + self.m
            a = a >> 1
        if a >= self.m:
            a = a - self.m
        return a


m = 750791094644726559640638407699
x1 = 540019781128412936473322405310
x2 = 515692107665463680305819378593

mont = Montgomery(m)
t1 = x1 * mont.rrm
t2 = x2 * mont.rrm

r1 = mont.reduce(t1)
r2 = mont.reduce(t2)
r = 1 << mont.n

print "b : ", Montgomery.BASE
print "n : ", mont.n
print "r : ", r
print "m : ", mont.m
print "t1: ", t1
print "t2: ", t2
print "r1: ", r1
print "r2: ", r2
print
print "Original x1       :", x1
print "Recovered from r1 :", mont.reduce(r1)
print "Original x2       :", x2
print "Recovered from r2 :", mont.reduce(r2)

print "\nMontgomery computation of x1 ^ x2 mod m:"
prod = mont.reduce(mont.rrm)
base = mont.reduce(x1 * mont.rrm)
exp = x2
while exp.bit_length() > 0:
    if (exp & 1) == 1:
        prod = mont.reduce(prod * base)
    exp = exp >> 1
    base = mont.reduce(base * base)
print mont.reduce(prod)
print "\nAlternate computation of x1 ^ x2 mod m :"
print pow(x1, x2, m)
Task: Finite state machine







Python: 

states = {  'ready':{
                'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
                'responses' : ['d','q']},
            'waiting':{
                'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
                'responses' : ['s','r']},
            'dispense' : {
                'prompt' : 'Machine dispensing: please (r)emove product',
                'responses' : ['r']},
            'refunding' : {
                'prompt' : 'Refunding money',
                'responses' : []},
            'exit' :{}
          }
transitions = { 'ready': { 
                    'd': 'waiting',
                    'q': 'exit'},
                'waiting' : {
                    's' : 'dispense',
                    'r' : 'refunding'},
                'dispense' : {
                    'r' : 'ready'},
                'refunding' : {
                    '' : 'ready'}}

def Acceptor(prompt, valids):
    
    if not valids: 
        print(prompt)
        return ''
    else:
        while True:
            resp = input(prompt)[0].lower()
            if resp in valids:
                return resp

def finite_state_machine(initial_state, exit_state):
    response = True
    next_state = initial_state
    current_state = states[next_state]
    while response != exit_state:
        response = Acceptor(current_state['prompt'], current_state['responses'])
        next_state = transitions[next_state][response]
        current_state = states[next_state]

if __name__ == "__main__":
    finite_state_machine('ready','q')
Task: Sokoban







Python: from array import array
from collections import deque
import psyco

data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""

def init(board):
    global data, nrows, sdata, ddata, px, py
    data = filter(None, board.splitlines())
    nrows = max(len(r) for r in data)

    maps = {' ':' ', '.': '.', '@':' ', '
    mapd = {' ':' ', '.': ' ', '@':'@', '

    for r, row in enumerate(data):
        for c, ch in enumerate(row):
            sdata += maps[ch]
            ddata += mapd[ch]
            if ch == '@':
                px = c
                py = r

def push(x, y, dx, dy, data):
    if sdata[(y+2*dy) * nrows + x+2*dx] == '
       data[(y+2*dy) * nrows + x+2*dx] != ' ':
        return None

    data2 = array("c", data)
    data2[y * nrows + x] = ' '
    data2[(y+dy) * nrows + x+dx] = '@'
    data2[(y+2*dy) * nrows + x+2*dx] = '*'
    return data2.tostring()

def is_solved(data):
    for i in xrange(len(data)):
        if (sdata[i] == '.') != (data[i] == '*'):
            return False
    return True

def solve():
    open = deque([(ddata, "", px, py)])
    visited = set([ddata])
    dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
            (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))

    lnrows = nrows
    while open:
        cur, csol, x, y = open.popleft()

        for di in dirs:
            temp = cur
            dx, dy = di[0], di[1]

            if temp[(y+dy) * lnrows + x+dx] == '*':
                temp = push(x, y, dx, dy, temp)
                if temp and temp not in visited:
                    if is_solved(temp):
                        return csol + di[3]
                    open.append((temp, csol + di[3], x+dx, y+dy))
                    visited.add(temp)
            else:
                if sdata[(y+dy) * lnrows + x+dx] == '
                   temp[(y+dy) * lnrows + x+dx] != ' ':
                    continue

                data2 = array("c", temp)
                data2[y * lnrows + x] = ' '
                data2[(y+dy) * lnrows + x+dx] = '@'
                temp = data2.tostring()

                if temp not in visited:
                    if is_solved(temp):
                        return csol + di[2]
                    open.append((temp, csol + di[2], x+dx, y+dy))
                    visited.add(temp)

    return "No solution"


level = """\









psyco.full()
init(level)
print level, "\n\n", solve()
Task: Zumkeller numbers







Python: from sympy import divisors

from sympy.combinatorics.subsets import Subset

def isZumkeller(n):
    d = divisors(n)
    s = sum(d)
    if not s % 2 and max(d) <= s/2:
        for x in range(1, 2**len(d)):
            if sum(Subset.unrank_binary(x, d).subset) == s/2:
                return True

    return False



def printZumkellers(N, oddonly=False):
    nprinted = 0
    for n in range(1, 10**5):
        if (oddonly == False or n % 2) and isZumkeller(n):
            print(f'{n:>8}', end='')
            nprinted += 1
            if nprinted % 10 == 0:
                print()
            if nprinted >= N:
                return


print("220 Zumkeller numbers:")
printZumkellers(220)
print("\n\n40 odd Zumkeller numbers:")
printZumkellers(40, True)
Task: Commatizing numbers







Python: import re as RegEx


def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
	outString = ""
	strPos = 0
	matches = RegEx.findall( "[0-9]*", _string )

	for match in matches[:-1]:
		if not match:
			outString += _string[ strPos ]
			strPos += 1
		else:
			if len(match) > _periodLen:
				leadIn = match[:_startPos]
				periods =  [ match [ i:i + _periodLen ] for i in range ( _startPos, len ( match ), _periodLen ) ]
				outString += leadIn + _separator.join( periods )
			else:
				outString += match

			strPos += len( match )

	return outString



print ( Commatize( "pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " " ) )
print ( Commatize( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "." ))
print ( Commatize( "\"-in Aus$+1411.8millions\"" ))
print ( Commatize( "===US$0017440 millions=== (in 2000 dollars)" ))
print ( Commatize( "123.e8000 is pretty big." ))
print ( Commatize( "The land area of the earth is 57268900(29% of the surface) square miles." ))
print ( Commatize( "Ain't no numbers in this here words, nohow, no way, Jose." ))
print ( Commatize( "James was never known as 0000000007" ))
print ( Commatize( "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe." ))
print ( Commatize( "␢␢␢$-140000±100 millions." ))
print ( Commatize( "6/9/1946 was a good year for some." ))
Task: Rare numbers







Python: 



from math import floor, sqrt
from datetime import datetime

def main():
	start = datetime.now()
	for i in xrange(1, 10 ** 11):
		if rare(i):
			print "found a rare:", i
	end = datetime.now()
	print "time elapsed:", end - start

def is_square(n):
	s = floor(sqrt(n + 0.5))
	return s * s == n

def reverse(n):
	return int(str(n)[::-1])

def is_palindrome(n):
	return n == reverse(n)

def rare(n):
	r = reverse(n)
	return ( 
		not is_palindrome(n) and 
		n > r and
		is_square(n+r) and is_square(n-r)
	)

if __name__ == '__main__':
	main()
Task: Suffix tree







Python: class Node:
    def __init__(self, sub="", children=None):
        self.sub = sub
        self.ch = children or []

class SuffixTree:
    def __init__(self, str):
        self.nodes = [Node()]
        for i in range(len(str)):
            self.addSuffix(str[i:])

    def addSuffix(self, suf):
        n = 0
        i = 0
        while i < len(suf):
            b = suf[i]
            x2 = 0
            while True:
                children = self.nodes[n].ch
                if x2 == len(children):
                    
                    n2 = len(self.nodes)
                    self.nodes.append(Node(suf[i:], []))
                    self.nodes[n].ch.append(n2)
                    return
                n2 = children[x2]
                if self.nodes[n2].sub[0] == b:
                    break
                x2 = x2 + 1

            
            sub2 = self.nodes[n2].sub
            j = 0
            while j < len(sub2):
                if suf[i + j] != sub2[j]:
                    
                    n3 = n2
                    
                    n2 = len(self.nodes)
                    self.nodes.append(Node(sub2[:j], [n3]))
                    self.nodes[n3].sub = sub2[j:] 
                    self.nodes[n].ch[x2] = n2
                    break 
                j = j + 1
            i = i + j   
            n = n2      

    def visualize(self):
        if len(self.nodes) == 0:
            print "<empty>"
            return

        def f(n, pre):
            children = self.nodes[n].ch
            if len(children) == 0:
                print "--", self.nodes[n].sub
                return
            print "+-", self.nodes[n].sub
            for c in children[:-1]:
                print pre, "+-",
                f(c, pre + " | ")
            print pre, "+-",
            f(children[-1], pre + "  ")

        f(0, "")

SuffixTree("banana$").visualize()
Task: Reflection_List properties







Python: class Parent(object):
    __priv = 'private'
    
    def __init__(self, name):
        self.name = name
    
    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, self.name)
    
    def doNothing(self):
        pass

import re

class Child(Parent):
    
    __rePrivate = re.compile('^_(Child|Parent)__')
    
    __reBleh = re.compile('\Wbleh$')
    @property
    def reBleh(self):
        return self.__reBleh
    
    def __init__(self, name, *args):
        super(Child, self).__init__(name)
        self.args = args
    
    def __dir__(self):
        myDir = filter(
            
            lambda p: not self.__rePrivate.match(p),
            list(set( \
                sum([dir(base) for base in type(self).__bases__], []) \
                + type(self).__dict__.keys() \
                + self.__dict__.keys() \
            )))
        return myDir + map(
            
            lambda p: p + '_bleh',
            filter(
                
                lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
                myDir))
    
    def __getattr__(self, name):
        if name[-5:] == '_bleh':
            
            return str(getattr(self, name[:-5])) + ' bleh'
        if hasattr(super(Child, chld), '__getattr__'):
            return super(Child, self).__getattr__(name)
        raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
    
    def __setattr__(self, name, value):
        if name[-5:] == '_bleh':
            
            if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
                setattr(self, name[:-5], self.reBleh.sub('', value))
        elif hasattr(super(Child, self), '__setattr__'):
            super(Child, self).__setattr__(name, value)
        elif hasattr(self, '__dict__'):
            self.__dict__[name] = value
    
    def __repr__(self):
        return '%s(%s, %s)' % (type(self).__name__, self.name, str(self.args).strip('[]()'))
    
    def doStuff(self):
        return (1+1.0/1e6) ** 1e6

par = Parent('par')
par.parent = True
dir(par)

inspect.getmembers(par)


chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
dir(chld)

inspect.getmembers(chld)
Task: Eertree







Python: 
from __future__ import print_function

class Node(object):
	def __init__(self):
		self.edges = {} 
		self.link = None 
		self.len = 0 

class Eertree(object):
	def __init__(self):
		self.nodes = []
		
		self.rto = Node() 
		self.rte = Node() 

		
		self.rto.link = self.rte.link = self.rto;
		self.rto.len = -1
		self.rte.len = 0
		self.S = [0] 
		self.maxSufT = self.rte 

	def get_max_suffix_pal(self, startNode, a):
		
		
		
		u = startNode
		i = len(self.S)
		k = u.len
		while id(u) != id(self.rto) and self.S[i - k - 1] != a:
			assert id(u) != id(u.link) 
			u = u.link
			k = u.len

		return u
	
	def add(self, a):

		
		
		
		
		Q = self.get_max_suffix_pal(self.maxSufT, a)

		
		createANewNode = not a in Q.edges

		if createANewNode:
			
			P = Node()
			self.nodes.append(P)
			P.len = Q.len + 2
			if P.len == 1:
				
				P.link = self.rte
			else:
				
				
				
				P.link = self.get_max_suffix_pal(Q.link, a).edges[a]

			
			Q.edges[a] = P

		
		self.maxSufT = Q.edges[a]

		
		self.S.append(a)

		return createANewNode
	
	def get_sub_palindromes(self, nd, nodesToHere, charsToHere, result):
		
		

		
		for lnkName in nd.edges:
			nd2 = nd.edges[lnkName] 
			self.get_sub_palindromes(nd2, nodesToHere+[nd2], charsToHere+[lnkName], result)

		
		if id(nd) != id(self.rto) and id(nd) != id(self.rte): 
			tmp = "".join(charsToHere)
			if id(nodesToHere[0]) == id(self.rte): 
				assembled = tmp[::-1] + tmp
			else: 
				assembled = tmp[::-1] + tmp[1:]
			result.append(assembled)

if __name__=="__main__":
	st = "eertree"
	print ("Processing string", st)
	eertree = Eertree()
	for ch in st:
		eertree.add(ch)

	print ("Number of sub-palindromes:", len(eertree.nodes))

	
	result = []
	eertree.get_sub_palindromes(eertree.rto, [eertree.rto], [], result) 
	eertree.get_sub_palindromes(eertree.rte, [eertree.rte], [], result) 
	print ("Sub-palindromes:", result)
Task: Base58Check encoding







Python: ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

def convertToBase58(num):
    sb = ''
    while (num > 0):
        r = num % 58
        sb = sb + ALPHABET[r]
        num = num // 58;
    return sb[::-1]

s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("%-56d -> %s" % (s, b))

hash_arr = [0x61, 0x626262, 0x636363, 0x73696d706c792061206c6f6e6720737472696e67, 0x516b6fcd0f, 0xbf4f89001e670274dd, 0x572e4794, 0xecac89cad93923c02321, 0x10c8511e]
for num in hash_arr:
    b = convertToBase58(num)
    print("0x%-54x -> %s" % (num, b))
Task: Latin Squares in reduced form







Python: def dList(n, start):
    start -= 1 
    a = range(n)
    a[start] = a[0]
    a[0] = start
    a[1:] = sorted(a[1:])
    first = a[1]
    
    r = []
    def recurse(last):
        if (last == first):
            
            
            
            for j,v in enumerate(a[1:]):
                if j + 1 == v:
                    return 
            b = [x + 1 for x in a]
            r.append(b)
            return
        for i in xrange(last, 0, -1):
            a[i], a[last] = a[last], a[i]
            recurse(last - 1)
            a[i], a[last] = a[last], a[i]
    recurse(n - 1)
    return r

def printSquare(latin,n):
    for row in latin:
        print row
    print

def reducedLatinSquares(n,echo):
    if n <= 0:
        if echo:
            print []
        return 0
    elif n == 1:
        if echo:
            print [1]
        return 1

    rlatin = [None] * n
    for i in xrange(n):
        rlatin[i] = [None] * n
    
    for j in xrange(0, n):
        rlatin[0][j] = j + 1

    class OuterScope:
        count = 0
    def recurse(i):
        rows = dList(n, i)

        for r in xrange(len(rows)):
            rlatin[i - 1] = rows[r]
            justContinue = False
            k = 0
            while not justContinue and k < i - 1:
                for j in xrange(1, n):
                    if rlatin[k][j] == rlatin[i - 1][j]:
                        if r < len(rows) - 1:
                            justContinue = True
                            break
                        if i > 2:
                            return
                k += 1
            if not justContinue:
                if i < n:
                    recurse(i + 1)
                else:
                    OuterScope.count += 1
                    if echo:
                        printSquare(rlatin, n)

    
    recurse(2)
    return OuterScope.count

def factorial(n):
    if n == 0:
        return 1
    prod = 1
    for i in xrange(2, n + 1):
        prod *= i
    return prod

print "The four reduced latin squares of order 4 are:\n"
reducedLatinSquares(4,True)

print "The size of the set of reduced latin squares for the following orders"
print "and hence the total number of latin squares of these orders are:\n"
for n in xrange(1, 7):
    size = reducedLatinSquares(n, False)
    f = factorial(n - 1)
    f *= f * n * size
    print "Order %d: Size %-4d x %d! x %d! => Total %d" % (n, size, n, n - 1, f)
Task: Kosaraju







Python: def kosaraju(g):
    class nonlocal: pass

    
    size = len(g)

    vis = [False]*size 
    l = [0]*size
    nonlocal.x = size
    t = [[]]*size   

    def visit(u):
        if not vis[u]:
            vis[u] = True
            for v in g[u]:
                visit(v)
                t[v] = t[v] + [u]
            nonlocal.x = nonlocal.x - 1
            l[nonlocal.x] = u

    
    for u in range(len(g)):
        visit(u)
    c = [0]*size

    def assign(u, root):
        if vis[u]:
            vis[u] = False
            c[u] = root
            for v in t[u]:
                assign(v, root)

    
    for u in l:
        assign(u, u)

    return c

g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)