WeixiangYan/CodeTransOcean huggingface dataset:
Task: Index finite lists of positive integers







Python: def rank(x): return int('a'.join(map(str, [1] + x)), 11)

def unrank(n):
	s = ''
	while n: s,n = "0123456789a"[n%11] + s, n//11
	return map(int, s.split('a'))[1:]

l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l
Task: Generate random numbers without repeating a value







Python: import random

print(random.sample(range(1, 21), 20))
Task: Safe and Sophie Germain primes







Python: print("working...")
row = 0
limit = 1500
Sophie = []

def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

for n in range(2,limit):
	p = 2*n + 1
	if isPrime(n) and isPrime(p):
		Sophie.append(n)

print("Found ",end = "")
print(len(Sophie),end = "")
print(" Safe and Sophie primes.")

print(Sophie)
print("done...")
Task: Goldbach's comet







Python: from matplotlib.pyplot import scatter, show
from sympy import isprime

def g(n):
    assert n > 2 and n % 2 == 0, 'n in goldbach function g(n) must be even'          
    count = 0
    for i in range(1, n//2 + 1):
        if isprime(i) and isprime(n - i):
            count += 1
    return count

print('The first 100 G numbers are:')
 
col = 1
for n in range(4, 204, 2):
    print(str(g(n)).ljust(4), end = '\n' if (col % 10 == 0) else '')
    col += 1

print('\nThe value of G(1000000) is', g(1_000_000))
 
x = range(4, 4002, 2)
y = [g(i) for i in x]
colors = [["red", "blue", "green"][(i // 2) % 3] for i in x]
scatter([i // 2 for i in x], y, marker='.', color = colors)
show()
Task: Cyclops numbers







Python: from sympy import isprime


def print50(a, width=8):
    for i, n in enumerate(a):
        print(f'{n: {width},}', end='\n' if (i + 1) % 10 == 0 else '')


def generate_cyclops(maxdig=9):
    yield 0
    for d in range((maxdig + 1) // 2):
        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]
        for left in arr:
            for right in arr:
                yield int(left + '0' + right)


def generate_prime_cyclops():
    for c in generate_cyclops():
        if isprime(c):
            yield c


def generate_blind_prime_cyclops():
    for c in generate_prime_cyclops():
        cstr = str(c)
        mid = len(cstr) // 2
        if isprime(int(cstr[:mid] + cstr[mid+1:])):
            yield c


def generate_palindromic_cyclops(maxdig=9):
    for d in range((maxdig + 1) // 2):
        arr = [str(i) for i in range(10**d, 10**(d+1)) if not('0' in str(i))]
        for s in arr:
            yield int(s + '0' + s[::-1])


def generate_palindromic_prime_cyclops():
    for c in generate_palindromic_cyclops():
        if isprime(c):
            yield c


print('The first 50 cyclops numbers are:')
gen = generate_cyclops()
print50([next(gen) for _ in range(50)])
for i, c in enumerate(generate_cyclops()):
    if c > 10000000:
        print(
            f'\nThe next cyclops number after 10,000,000 is {c} at position {i:,}.')
        break

print('\nThe first 50 prime cyclops numbers are:')
gen = generate_prime_cyclops()
print50([next(gen) for _ in range(50)])
for i, c in enumerate(generate_prime_cyclops()):
    if c > 10000000:
        print(
            f'\nThe next prime cyclops number after 10,000,000 is {c} at position {i:,}.')
        break

print('\nThe first 50 blind prime cyclops numbers are:')
gen = generate_blind_prime_cyclops()
print50([next(gen) for _ in range(50)])
for i, c in enumerate(generate_blind_prime_cyclops()):
    if c > 10000000:
        print(
            f'\nThe next blind prime cyclops number after 10,000,000 is {c} at position {i:,}.')
        break

print('\nThe first 50 palindromic prime cyclops numbers are:')
gen = generate_palindromic_prime_cyclops()
print50([next(gen) for _ in range(50)], 11)
for i, c in enumerate(generate_palindromic_prime_cyclops()):
    if c > 10000000:
        print(
            f'\nThe next palindromic prime cyclops number after 10,000,000 is {c} at position {i}.')
        break
Task: Conjugate a Latin verb







Python: 

 
def conjugate(infinitive): 
    if not infinitive[-3:] == "are":
        print("'", infinitive, "' non prima coniugatio verbi.\n", sep='')
        return False
    
    stem = infinitive[0:-3]
    if len(stem) == 0:
        print("\'", infinitive, "\' non satis diu conjugatus\n", sep='')
        return False

    print("Praesens indicativi temporis of '", infinitive, "':", sep='') 
    for ending in ("o", "as", "at", "amus", "atis", "ant"):
        print("     ", stem, ending, sep='')
    print()
 
 
if __name__ == '__main__':
    for infinitive in ("amare", "dare", "qwerty", "are"):
        conjugate(infinitive)
Task: Prime numbers which contain 123







Python: 

def prime(limite, mostrar):
    global columna
    columna = 0
    
    for n in range(limite):
        strn = str(n)
        if isPrime(n) and ('123' in str(n)):
            columna += 1                
            if mostrar == True:
                print(n, end="  ");
                if columna % 8 == 0:
                    print('')
    return columna


if __name__ == "__main__":
    print("Números primos que contienen 123:")
    limite = 100000
    prime(limite, True)
    print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
    limite = 1000000
    prime(limite, False)
    print("\n\nEncontrados ", columna, " números primos por debajo de", limite)
Task: Prime triplets







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

if __name__ == '__main__':
    for p in range(3, 5499, 2):
        if not isPrime(p+6):
            continue
        if not isPrime(p+2):
            continue
        if not isPrime(p):
            continue
        print(f'[{p} {p+2} {p+6}]')
Task: Neighbour primes







Python: 

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True


if __name__ == '__main__':
    print("p        q       pq+2")
    print("-----------------------")
    for p in range(2, 499):
        if not isPrime(p):
            continue
        q = p + 1
        while not isPrime(q):
            q += 1
        if not isPrime(2 + p*q):
            continue 
        print(p, "\t", q, "\t", 2+p*q)
Task: Collect and sort square numbers in ascending order from three lists







Python: import math

print("working...")
list = [(3,4,34,25,9,12,36,56,36),(2,8,81,169,34,55,76,49,7),(75,121,75,144,35,16,46,35)]
Squares = []

def issquare(x):
	for p in range(x):
		if x == p*p:
			return 1
for n in range(3):
	for m in range(len(list[n])):
		if issquare(list[n][m]):
			Squares.append(list[n][m])

Squares.sort()
print(Squares)
print("done...")
Task: Composite numbers k with no single digit factors whose factors are all substrings of k







Python: from sympy import isprime, factorint

def contains_its_prime_factors_all_over_7(n):
    if n < 10 or isprime(n):
        return False
    strn = str(n)
    pfacs = factorint(n).keys()
    return all(f > 9 and str(f) in strn for f in pfacs)

found = 0
for n in range(1_000_000_000):
    if contains_its_prime_factors_all_over_7(n):
        found += 1
        print(f'{n: 12,}', end = '\n' if found % 10 == 0 else '')
        if found == 20:
            break
Task: Magic constant







Python: 

def a(n):
    n += 2
    return n*(n**2 + 1)/2
 
def inv_a(x):
    k = 0
    while k*(k**2+1)/2+2 < x:
        k+=1
    return k

 
if __name__ == '__main__':
    print("The first 20 magic constants are:");
    for n in range(1, 20):
        print(int(a(n)), end = " ");
    print("\nThe 1,000th magic constant is:",int(a(1000)));
     
    for e in range(1, 20):
        print(f'10^{e}: {inv_a(10**e)}');
Task: Cullen and Woodall numbers







Python: print("working...")
print("First 20 Cullen numbers:")

for n in range(1,21):
    num = n*pow(2,n)+1
    print(str(num),end= " ")

print()
print("First 20 Woodall numbers:")

for n in range(1,21):
    num = n*pow(2,n)-1
    print(str(num),end=" ")

print()
print("done...")
Task: Long literals, with continuations







Python: 

revision = "October 13th 2020"




elements = (
    "hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine "
    "neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon "
    "potassium calcium scandium titanium vanadium chromium manganese iron "
    "cobalt nickel copper zinc gallium germanium arsenic selenium bromine "
    "krypton rubidium strontium yttrium zirconium niobium molybdenum "
    "technetium ruthenium rhodium palladium silver cadmium indium tin "
    "antimony tellurium iodine xenon cesium barium lanthanum cerium "
    "praseodymium neodymium promethium samarium europium gadolinium terbium "
    "dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum "
    "tungsten rhenium osmium iridium platinum gold mercury thallium lead "
    "bismuth polonium astatine radon francium radium actinium thorium "
    "protactinium uranium neptunium plutonium americium curium berkelium "
    "californium einsteinium fermium mendelevium nobelium lawrencium "
    "rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium "
    "roentgenium copernicium nihonium flerovium moscovium livermorium "
    "tennessine oganesson"
)


def report():
    
    items = elements.split()

    print(f"Last revision date: {revision}")
    print(f"Number of elements: {len(items)}")
    print(f"Last element      : {items[-1]}")


if __name__ == "__main__":
    report()
Task: Hex words







Python: def digroot(n):
    while n > 9:
        n = sum([int(d) for d in str(n)])
    return n

with open('unixdict.txt') as f:
    lines = [w.strip() for w in f.readlines()]
    words = [w for w in lines if len(w) >= 4 and all(c in 'abcdef' for c in w)]
    results = [[w, int(w, 16)] for w in words]
    for a in results:
        a.append(digroot(a[1]))
        
    print(f"Hex words in unixdict.txt:\nRoot  Word      Base 10\n", "-"*22)
    for a in sorted(results, key=lambda x:x[2]):
        print(f"{a[2]}     {a[0]:6}{a[1]:10}")
        
    print("Total count of these words:", len(results))
    print("\nHex words with > 3 distinct letters:\nRoot  Word      Base 10\n", "-"*22)
    results = [a for a in results if len(set(str(a[0]))) > 3]
    for a in sorted(results, key=lambda x:x[2]):
        print(f"{a[2]}     {a[0]:6}{a[1]:10}")
        
    print("Total count of those words:", len(results))
Task: Find minimum number of coins that make a given value







Python: def makechange(denominations = [1,2,5,10,20,50,100,200], total = 988):
    print(f"Available denominations: {denominations}. Total is to be: {total}.")
    coins, remaining = sorted(denominations, reverse=True), total
    for n in range(len(coins)):
        coinsused, remaining = divmod(remaining, coins[n])
        if coinsused > 0:
            print("   ", coinsused, "*", coins[n])

makechange()
Task: Longest palindromic substrings







Python: 



def longestPalindromes(s):
    
    k = s.lower()
    palindromes = [
        palExpansion(k)(ab) for ab
        in palindromicNuclei(k)
    ]
    maxLength = max([
        len(x) for x in palindromes
    ]) if palindromes else 1
    return (
        [
            x for x in palindromes if maxLength == len(x)
        ] if palindromes else list(s),
        maxLength
    ) if s else ([], 0)



def palindromicNuclei(s):
    
    cs = list(s)
    return [
        
        (i, 1 + i) for (i, (a, b))
        in enumerate(zip(cs, cs[1:]))
        if a == b
    ] + [
        
        (i, 2 + i) for (i, (a, b, c))
        in enumerate(zip(cs, cs[1:], cs[2:]))
        if a == c
    ]



def palExpansion(s):
    
    iEnd = len(s) - 1

    def limit(ij):
        i, j = ij
        return 0 == i or iEnd == j or s[i-1] != s[j+1]

    def expansion(ij):
        i, j = ij
        return (i - 1, 1 + j)

    def go(ij):
        ab = until(limit)(expansion)(ij)
        return s[ab[0]:ab[1] + 1]
    return go




def main():
    
    print(
        fTable(main.__doc__ + ':\n')(repr)(repr)(
            longestPalindromes
        )([
            'three old rotators',
            'never reverse',
            'stable was I ere I saw elbatrosses',
            'abracadabra',
            'drome',
            'the abbatial palace',
            ''
        ])
    )





def until(p):
    
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go






def fTable(s):
    
    def gox(xShow):
        def gofx(fxShow):
            def gof(f):
                def goxs(xs):
                    ys = [xShow(x) for x in xs]
                    w = max(map(len, ys))

                    def arrowed(x, y):
                        return y.rjust(w, ' ') + ' -> ' + (
                            fxShow(f(x))
                        )
                    return s + '\n' + '\n'.join(
                        map(arrowed, xs, ys)
                    )
                return goxs
            return gof
        return gofx
    return gox



if __name__ == '__main__':
    main()
Task: Find squares n where n+1 is prime







Python: limit = 1000
print("working...")

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def issquare(x):
	for n in range(1,x+1):
		if (x == n*n):
			return 1
	return 0

for n in range(limit-1):
	if issquare(n) and isprime(n+1):
		print(n,end=" ")

print()
print("done...")
Task: Window management







Python: from tkinter import *
import tkinter.messagebox

def maximise():
	
	root.geometry("{}x{}+{}+{}".format(root.winfo_screenwidth(), root.winfo_screenheight(), 0, 0))
	
def minimise():
	
	root.iconify()
	
def delete():
	
	if tkinter.messagebox.askokcancel("OK/Cancel","Are you sure?"):
		root.quit()
	
root = Tk()

mx=Button(root,text="maximise",command=maximise)
mx.grid()
mx.bind(maximise)

mn=Button(root,text="minimise",command=minimise)
mn.grid()
mn.bind(minimise)


root.protocol("WM_DELETE_WINDOW",delete)

mainloop()
Task: Galton box animation







Python: 

import sys, os
import random
import time

def print_there(x, y, text):
     sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
     sys.stdout.flush()


class Ball():
    def __init__(self):
        self.x = 0
        self.y = 0
        
    def update(self):
        self.x += random.randint(0,1)
        self.y += 1

    def fall(self):
        self.y +=1


class Board():
    def __init__(self, width, well_depth, N):
        self.balls = []
        self.fallen = [0] * (width + 1)
        self.width = width
        self.well_depth = well_depth
        self.N = N
        self.shift = 4
        
    def update(self):
        for ball in self.balls:
            if ball.y < self.width:
                ball.update()
            elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:
                ball.fall()
            elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:
                self.fallen[ball.x] += 1
            else:
                pass
                
    def balls_on_board(self):
        return len(self.balls) - sum(self.fallen)
                
    def add_ball(self):
        if(len(self.balls) <= self.N):
            self.balls.append(Ball())

    def print_board(self):
        for y in range(self.width + 1):
            for x in range(y):
                print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "
    def print_ball(self, ball):
        if ball.y <= self.width:
            x = self.width - ball.y + 2*ball.x + self.shift
        else:
            x = 2*ball.x + self.shift
        y = ball.y + 1
        print_there(y, x, "*")
         
    def print_all(self):
        print(chr(27) + "[2J")
        self.print_board();
        for ball in self.balls:
            self.print_ball(ball)


def main():
    board = Board(width = 15, well_depth = 5, N = 10)
    board.add_ball() 
    while(board.balls_on_board() > 0):
         board.print_all()
         time.sleep(0.25)
         board.update()
         board.print_all()
         time.sleep(0.25)
         board.update()
         board.add_ball()


if __name__=="__main__":
    main()
Task: Primes - allocate descendants to their ancestors







Python: from __future__ import print_function
from itertools import takewhile

maxsum = 99

def get_primes(max):
    if max < 2:
        return []
    lprimes = [2]
    for x in range(3, max + 1, 2):
        for p in lprimes:
            if x % p == 0:
                break
        else:
            lprimes.append(x)
    return lprimes

descendants = [[] for _ in range(maxsum + 1)]
ancestors = [[] for _ in range(maxsum + 1)]

primes = get_primes(maxsum)

for p in primes:
    descendants[p].append(p)
    for s in range(1, len(descendants) - p):
        descendants[s + p] += [p * pr for pr in descendants[s]]

for p in primes + [4]:
    descendants[p].pop()

total = 0
for s in range(1, maxsum + 1):
    descendants[s].sort()
    for d in takewhile(lambda x: x <= maxsum, descendants[s]):
        ancestors[d] = ancestors[s] + [s]
    print([s], "Level:", len(ancestors[s]))
    print("Ancestors:", ancestors[s] if len(ancestors[s]) else "None")
    print("Descendants:", len(descendants[s]) if len(descendants[s]) else "None")
    if len(descendants[s]):
        print(descendants[s])
    print()
    total += len(descendants[s])

print("Total descendants", total)
Task: Sorting Algorithms_Circle Sort







Python: 




def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
    
    n = R-L
    if n < 2:
        return 0
    swaps = 0
    m = n//2
    for i in range(m):
        if A[R-(i+1)] < A[L+i]:
            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
            swaps += 1
    if (n & 1) and (A[L+m] < A[L+m-1]):
        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
        swaps += 1
    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)

def circle_sort(L:list)->'sort A in place, returning the number of swaps':
    swaps = 0
    s = 1
    while s:
        s = circle_sort_backend(L, 0, len(L))
        swaps += s
    return swaps


if __name__ == '__main__':
    from random import shuffle
    for i in range(309):
        L = list(range(i))
        M = L[:]
        shuffle(L)
        N = L[:]
        circle_sort(L)
        if L != M:
            print(len(L))
            print(N)
            print(L)
Task: Word wheel







Python: import urllib.request
from collections import Counter


GRID = 


def getwords(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'):
    "Return lowercased words of 3 to 9 characters"
    words = urllib.request.urlopen(url).read().decode().strip().lower().split()
    return (w for w in words if 2 < len(w) < 10)

def solve(grid, dictionary):
    gridcount = Counter(grid)
    mid = grid[4]
    return [word for word in dictionary
            if mid in word and not (Counter(word) - gridcount)]


if __name__ == '__main__':
    chars = ''.join(GRID.strip().lower().split())
    found = solve(chars, dictionary=getwords())
    print('\n'.join(found))
Task: Intersecting number wheels







Python: from itertools import islice

class INW():
    

    def __init__(self, **wheels):
        self._wheels = wheels
        self.isect = {name: self._wstate(name, wheel) 
                      for name, wheel in wheels.items()}
    
    def _wstate(self, name, wheel):
        "Wheel state holder"
        assert all(val in self._wheels for val in wheel if type(val) == str), \
               f"ERROR: Interconnected wheel not found in {name}: {wheel}"
        pos = 0
        ln = len(wheel)
        while True:
            nxt, pos = wheel[pos % ln], pos + 1
            yield next(self.isect[nxt]) if type(nxt) == str else nxt
                
    def __iter__(self):
        base_wheel_name = next(self.isect.__iter__())
        yield from self.isect[base_wheel_name]
        
    def __repr__(self):
        return f"{self.__class__.__name__}({self._wheels})"
    
    def __str__(self):
        txt = "Intersecting Number Wheel group:"
        for name, wheel in self._wheels.items():
            txt += f"\n  {name+':':4}" + ' '.join(str(v) for v in wheel)
        return txt

def first(iter, n):
    "Pretty print first few terms"
    return ' '.join(f"{nxt}" for nxt in islice(iter, n))

if __name__ == '__main__':
    for group in[
      {'A': (1, 2, 3)},
      {'A': (1, 'B', 2),
       'B': (3, 4)},
      {'A': (1, 'D', 'D'),
       'D': (6, 7, 8)},
      {'A': (1, 'B', 'C'),
       'B': (3, 4),
       'C': (5, 'B')}, 
     ]:
        w = INW(**group)
        print(f"{w}\n  Generates:\n    {first(w, 20)} ...\n")
Task: Yahoo! search interface







Python: import urllib
import re

def fix(x):
    p = re.compile(r'<[^<]*?>')
    return p.sub('', x).replace('&amp;', '&')
 
class YahooSearch:
    def __init__(self, query, page=1):       
        self.query = query
        self.page = page
        self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.page - 1) * 10 + 1))
        self.content = urllib.urlopen(self.url).read()        
 
    def getresults(self):
        self.results = []
 
        for i in re.findall('<a class="yschttl spt" href=".+?">(.+?)</a></h3></div>(.+?)</div>.*?<span class=url>(.+?)</span>', self.content):
 
            title = fix(i[0])
            content = fix(i[1])
            url = fix(i[2])
 
            self.results.append(YahooResult(title, content, url))
 
        return self.results
 
    def getnextpage(self):
        return YahooSearch(self.query, self.page+1)
 
    search_results = property(fget=getresults)
    nextpage = property(fget=getnextpage)
 
class YahooResult:
    def __init__(self,title,content,url):
        self.title = title
        self.content = content
        self.url = url
 

 
x = YahooSearch("test")
 
for result in x.search_results:
    print result.title
Task: Circles of given radius through two points







Python: from collections import namedtuple
from math import sqrt

Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')

def circles_from_p1p2r(p1, p2, r):
    'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
    if r == 0.0:
        raise ValueError('radius of zero')
    (x1, y1), (x2, y2) = p1, p2
    if p1 == p2:
        raise ValueError('coincident points gives infinite number of Circles')
    
    dx, dy = x2 - x1, y2 - y1
    
    q = sqrt(dx**2 + dy**2)
    if q > 2.0*r:
        raise ValueError('separation of points > diameter')
    
    x3, y3 = (x1+x2)/2, (y1+y2)/2
    
    d = sqrt(r**2-(q/2)**2)
    
    c1 = Cir(x = x3 - d*dy/q,
             y = y3 + d*dx/q,
             r = abs(r))
    
    c2 = Cir(x = x3 + d*dy/q,
             y = y3 - d*dx/q,
             r = abs(r))
    return c1, c2

if __name__ == '__main__':
    for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0),
                      (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0),
                      (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0),
                      (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5),
                      (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]:
        print('Through points:\n  %r,\n  %r\n  and radius %f\nYou can construct the following circles:'
              % (p1, p2, r))
        try:
            print('  %r\n  %r\n' % circles_from_p1p2r(p1, p2, r))
        except ValueError as v:
            print('  ERROR: %s\n' % (v.args[0],))