WeixiangYan/CodeTransOcean huggingface dataset:
Task: War card game







Python: 

from numpy.random import shuffle

SUITS = ['♣', '♦', '♥', '♠']
FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
DECK = [f + s for f in FACES for s in SUITS]
CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))


class WarCardGame:
    
    def __init__(self):
        deck = DECK.copy()
        shuffle(deck)
        self.deck1, self.deck2 = deck[:26], deck[26:]
        self.pending = []

    def turn(self):
        
        if len(self.deck1) == 0 or len(self.deck2) == 0:
            return self.gameover()

        card1, card2 = self.deck1.pop(0), self.deck2.pop(0)
        rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]
        print("{:10}{:10}".format(card1, card2), end='')
        if rank1 > rank2:
            print('Player 1 takes the cards.')
            self.deck1.extend([card1, card2])
            self.deck1.extend(self.pending)
            self.pending = []
        elif rank1 < rank2:
            print('Player 2 takes the cards.')
            self.deck2.extend([card2, card1])
            self.deck2.extend(self.pending)
            self.pending = []
        else:  
            print('Tie!')
            if len(self.deck1) == 0 or len(self.deck2) == 0:
                return self.gameover()

            card3, card4 = self.deck1.pop(0), self.deck2.pop(0)
            self.pending.extend([card1, card2, card3, card4])
            print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='')
            return self.turn()

        return True

    def gameover(self):
        
        if len(self.deck2) == 0:
            if len(self.deck1) == 0:
                print('\nGame ends as a tie.')
            else:
                print('\nPlayer 1 wins the game.')
        else:
            print('\nPlayer 2 wins the game.')

        return False


if __name__ == '__main__':
    WG = WarCardGame()
    while WG.turn():
        continue
Task: Determine sentence type







Python: import re

txt = 

def haspunctotype(s):
    return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N'

txt = re.sub('\n', '', txt)
pars = [s.strip() for s in re.split("(?:(?:(?<=[\?\!\.])(?:))|(?:(?:)(?=[\?\!\.])))", txt)]
if len(pars) % 2:
    pars.append('')  
for i in range(0, len(pars)-1, 2):
    print((pars[i] + pars[i + 1]).ljust(54), "==>", haspunctotype(pars[i + 1]))
Task: Random sentence from book







Python: from urllib.request import urlopen
import re
from string import punctuation
from collections import Counter, defaultdict
import random



text_url = 'http://www.gutenberg.org/files/36/36-0.txt'
text_start = 'No one would have believed'

sentence_ending = '.!?'
sentence_pausing = ',;:'

def read_book(text_url, text_start) -> str:
    with urlopen(text_url) as book:
        text = book.read().decode('utf-8')
    return text[text.index(text_start):]

def remove_punctuation(text: str, keep=sentence_ending+sentence_pausing)-> str:
    "Remove punctuation, keeping some"
    to_remove = ''.join(set(punctuation) - set(keep))
    text = text.translate(str.maketrans(to_remove, ' ' * len(to_remove))).strip()
    text = re.sub(fr"[^a-zA-Z0-9{keep}\n ]+", ' ', text)
    
    if keep:
        text = re.sub(f"([{keep}])+", r" \1 ", text).strip()
    if text[-1] not in sentence_ending:
        text += ' .'
    return text.lower()

def word_follows_words(txt_with_pauses_and_endings):
    "return dict of freq of words following one/two words"
    words = ['.'] + txt_with_pauses_and_endings.strip().split()

    
    word2next = defaultdict(lambda :defaultdict(int))
    word2next2 = defaultdict(lambda :defaultdict(int))
    for lh, rh in zip(words, words[1:]):
        word2next[lh][rh] += 1
    for lh, mid, rh in zip(words, words[1:], words[2:]):
        word2next2[(lh, mid)][rh] += 1

    return dict(word2next), dict(word2next2)

def gen_sentence(word2next, word2next2) -> str:

    s = ['.']
    s += random.choices(*zip(*word2next[s[-1]].items()))
    while True:
        s += random.choices(*zip(*word2next2[(s[-2], s[-1])].items()))
        if s[-1] in sentence_ending:
            break

    s  = ' '.join(s[1:]).capitalize()
    s = re.sub(fr" ([{sentence_ending+sentence_pausing}])", r'\1', s)
    s = re.sub(r" re\b", "'re", s)
    s = re.sub(r" s\b", "'s", s)
    s = re.sub(r"\bi\b", "I", s)

    return s

if __name__ == "__main__":
    txt_with_pauses_and_endings = remove_punctuation(read_book(text_url, text_start))
    word2next, word2next2 = word_follows_words(txt_with_pauses_and_endings)
    
    sentence = gen_sentence(word2next, word2next2)
    print(sentence)
Task: Smallest multiple







Python: 

from math import gcd
from functools import reduce


def lcm(a, b):
    
    return 0 if 0 == a or 0 == b else (
        abs(a * b) // gcd(a, b)
    )


for i in [10, 20, 200, 2000]:
    print(str(i) + ':', reduce(lcm, range(1, i + 1)))
Task: Find first missing positive







Python: 

from itertools import count



def firstGap(xs):
    
    return next(x for x in count(1) if x not in xs)




def main():
    
    print('\n'.join([
        f'{repr(xs)} -> {firstGap(xs)}' for xs in [
            [1, 2, 0],
            [3, 4, -1, 1],
            [7, 8, 9, 11, 12]
        ]
    ]))



if __name__ == '__main__':
    main()
Task: Find adjacent primes which differ by a square integer







Python: import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0

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(x):
		if (x == n*n):
			return 1
	return 0

for n in range(limit):
    if isPrime(n):
       Primes.append(n)

for n in range(2,len(Primes)):
    pr1 = Primes[n]
    pr2 = Primes[n-1]
    diff = pr1 - pr2
    flag = issquare(diff)
    if (flag == 1 and diff > 36):
       print(str(pr1) + " " + str(pr2) + " diff = " + str(diff))

print("done...")
Task: Compiler_syntax analyzer







Python: def expr(p)
    if tok is "("
        x = paren_expr()
    elif tok in ["-", "+", "!"]
        gettok()
        y = expr(precedence of operator)
        if operator was "+"
            x = y
        else
            x = make_node(operator, y)
    elif tok is an Identifier
        x = make_leaf(Identifier, variable name)
        gettok()
    elif tok is an Integer constant
        x = make_leaf(Integer, integer value)
        gettok()
    else
        error()

    while tok is a binary operator and precedence of tok >= p
        save_tok = tok
        gettok()
        q = precedence of save_tok
        if save_tok is not right associative
            q += 1
        x = make_node(Operator save_tok represents, x, expr(q))

    return x

def paren_expr()
    expect("(")
    x = expr(0)
    expect(")")
    return x

def stmt()
    t = NULL
    if accept("if")
        e = paren_expr()
        s = stmt()
        t = make_node(If, e, make_node(If, s, accept("else") ? stmt() : NULL))
    elif accept("putc")
        t = make_node(Prtc, paren_expr())
        expect(";")
    elif accept("print")
        expect("(")
        repeat
            if tok is a string
                e = make_node(Prts, make_leaf(String, the string))
                gettok()
            else
                e = make_node(Prti, expr(0))

            t = make_node(Sequence, t, e)
        until not accept(",")
        expect(")")
        expect(";")
    elif tok is ";"
        gettok()
    elif tok is an Identifier
        v = make_leaf(Identifier, variable name)
        gettok()
        expect("=")
        t = make_node(Assign, v, expr(0))
        expect(";")
    elif accept("while")
        e = paren_expr()
        t = make_node(While, e, stmt()
    elif accept("{")
        while tok not equal "}" and tok not equal end-of-file
            t = make_node(Sequence, t, stmt())
        expect("}")
    elif tok is end-of-file
        pass
    else
        error()
    return t

def parse()
    t = NULL
    gettok()
    repeat
        t = make_node(Sequence, t, stmt())
    until tok is end-of-file
    return t
Task: Snake and ladder







Python: import random
import sys

snl = {
    4: 14,
    9: 31,
    17: 7,
    20: 38,
    28: 84,
    40: 59,
    51: 67,
    54: 34,
    62: 19,
    63: 81,
    64: 60,
    71: 91,
    87: 24,
    93: 73,
    95: 75,
    99: 78
}
sixesRollAgain = True

def turn(player, square):
    while True:
        roll = random.randint(1,6)
        sys.stdout.write("Player {0} on square {1}, rolls a {2}".format(player, square, roll))
        if square + roll > 100:
            print " but cannot move."
        else:
            square += roll
            print " and moves to square {0}".format(square)
            if square == 100:
                return 100
            next = snl.get(square, square)
            if square < next:
                print "Yay! landed on a ladder. Climb up to {0}.".format(next)
                if square == 100:
                    return 100
                square = next
            elif square > next:
                print "Oops! Landed on a snake. Slither down to {0}.".format(next)
                square = next
        if roll < 6 or not sixesRollAgain:
            return square
        print "Rolled a 6 so roll again."

def main():
    players = [1, 1, 1]
    while True:
        for i in range(0, 3):
            ns = turn(i+1, players[i])
            if ns == 100:
                print "Player {0} wins!".format(i+1)
                return
            players[i] = ns;
            print

main()
Task: Implicit type conversion







Python: from fractions import Fraction
from decimal import Decimal, getcontext
getcontext().prec = 60
from itertools import product

casting_functions = [int, float, complex,   
                     Fraction, Decimal,     
                     hex, oct, bin,         
                     bool,                  
                     iter,                  
                     list, tuple, range,    
                     str, bytes,            
                     bytearray,             
                     set, frozenset,        
                     dict,                  
                    ]

examples_of_types = [0, 42, 
                     0.0 -0.0, 12.34, 56.0, 
                     (0+0j), (1+2j), (1+0j), (78.9+0j), (0+1.2j),
                     Fraction(0, 1), Fraction(22, 7), Fraction(4, 2), 
                     Decimal('0'),
                     Decimal('3.14159265358979323846264338327950288419716939937510'),
                     Decimal('1'), Decimal('1.5'),
                     True, False,
                     iter(()), iter([1, 2, 3]), iter({'A', 'B', 'C'}), 
                     iter([[1, 2], [3, 4]]), iter((('a', 1), (2, 'b'))),
                     [], [1, 2], [[1, 2], [3, 4]],
                     (), (1, 'two', (3+0j)), (('a', 1), (2, 'b')),
                     range(0), range(3),
                     "", "A", "ABBA", "Milü",
                     b"", b"A", b"ABBA",
                     bytearray(b""), bytearray(b"A"), bytearray(b"ABBA"),
                     set(), {1, 'two', (3+0j), (4, 5, 6)},
                     frozenset(), frozenset({1, 'two', (3+0j), (4, 5, 6)}),
                     {}, {1: 'one', 'two': (2+3j), ('RC', 3): None} 
                    ]
if __name__ == '__main__':
    print('Common Python types/type casting functions:')
    print('  ' + '\n  '.join(f.__name__ for f in casting_functions))
    print('\nExamples of those types:')
    print('  ' + '\n  '.join('%-26s %r' % (type(e), e) for e in examples_of_types))
    print('\nCasts of the examples:')
    for f, e in product(casting_functions, examples_of_types):
        try:
            ans = f(e)
        except BaseException:
            ans = 'EXCEPTION RAISED!'
        print('%-60s -> %r' % ('%s(%r)' % (f.__name__, e), ans))
Task: Compiler_code generator







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

    text = line_list[0] 

    if text == ";"
        return None

    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: Mersenne primes







Python: import random


def MillerRabinPrimalityTest(number):
    
    if number == 2:
        return True
    elif number == 1 or number % 2 == 0:
        return False
    
    
    
    
    oddPartOfNumber = number - 1
    
    
    timesTwoDividNumber = 0
    
    
    while oddPartOfNumber % 2 == 0:
        oddPartOfNumber = oddPartOfNumber / 2
        timesTwoDividNumber = timesTwoDividNumber + 1 
     
    
    for time in range(3):
        
        
        while True:
            
            randomNumber = random.randint(2, number)-1
            if randomNumber != 0 and randomNumber != 1:
                break
        
        
        randomNumberWithPower = pow(randomNumber, oddPartOfNumber, number)
        
        
        if (randomNumberWithPower != 1) and (randomNumberWithPower != number - 1):
            
            iterationNumber = 1
            
            
            while (iterationNumber <= timesTwoDividNumber - 1) and (randomNumberWithPower != number - 1):
                
                randomNumberWithPower = pow(randomNumberWithPower, 2, number)
                
                
                iterationNumber = iterationNumber + 1
            
            if (randomNumberWithPower != (number - 1)):
                return False
            
    
    return True


MAX = 20
p = 2
count = 0
while True:
    m = (2 << (p - 1)) - 1
    if MillerRabinPrimalityTest(m):
        print "2 ^ {} - 1".format(p)
        count = count + 1
        if count == MAX:
            break
    
    while True:
        p = p + 2 if (p > 2) else 3
        if MillerRabinPrimalityTest(p):
            break
print "done"
Task: Cubic special 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__':
    p = 2
    n = 1

    print("2",end = " ")
    while True:
        if isPrime(p + n**3):
            p += n**3
            n = 1
            print(p,end = " ")
        else:
            n += 1
        if p + n**3 >= 15000:
            break
Task: Sexy primes







Python: LIMIT = 1_000_035
def primes2(limit=LIMIT):
    if limit < 2: return []
    if limit < 3: return [2]
    lmtbf = (limit - 3) // 2
    buf = [True] * (lmtbf + 1)
    for i in range((int(limit ** 0.5) - 3) // 2 + 1):
        if buf[i]:
            p = i + i + 3
            s = p * (i + 1) + i
            buf[s::p] = [False] * ((lmtbf - s) // p + 1)
    return [2] + [i + i + 3 for i, v in enumerate(buf) if v]

primes = primes2(LIMIT +6)
primeset = set(primes)
primearray = [n in primeset for n in range(LIMIT)]


s = [[] for x in range(4)]
unsexy = []

for p in primes:
    if p > LIMIT:
        break
    if p + 6 in primeset and p + 6 < LIMIT:
        s[0].append((p, p+6))
    elif p + 6 in primeset:
        break
    else:
        if p - 6 not in primeset:
            unsexy.append(p)
        continue
    if p + 12 in primeset and p + 12 < LIMIT:
        s[1].append((p, p+6, p+12))
    else:
        continue
    if p + 18 in primeset and p + 18 < LIMIT:
        s[2].append((p, p+6, p+12, p+18))
    else:
        continue
    if p + 24 in primeset and p + 24 < LIMIT:
        s[3].append((p, p+6, p+12, p+18, p+24))


print('"SEXY" PRIME GROUPINGS:')
for sexy, name in zip(s, 'pairs triplets quadruplets quintuplets'.split()):
    print(f'  {len(sexy)} {na (not isPrime(n-6))))) |> Array.ofSeq
printfn "There are %d unsexy primes less than 1,000,035. The last 10 are:" n.Length
Array.skip (n.Length-10) n |> Array.iter(fun n->printf "%d " n); printfn ""
let ni=pCache |> Seq.takeWhile(fun n->nme} ending with ...')
    for sx in sexy[-5:]:
        print('   ',sx)

print(f'\nThere are {len(unsexy)} unsexy primes ending with ...')
for usx in unsexy[-10:]:
    print(' ',usx)
Task: Taxicab numbers







Python: from collections import defaultdict
from itertools import product
from pprint import pprint as pp

cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
	if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
	
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)


for t in enumerate(taxied[:25], 1):
    pp(t)
print('...')    
for t in enumerate(taxied[2000-1:2000+6], 2000):
    pp(t)
Task: Strong and weak primes







Python: import numpy as np

def primesfrom2to(n):
    
    
    sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in range(int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)//3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

p = primes10m   = primesfrom2to(10_000_000)
s = strong10m   = [t for s, t, u in zip(p, p[1:], p[2:]) 
                   if t > (s + u) / 2]
w = weak10m     = [t for s, t, u in zip(p, p[1:], p[2:]) 
                   if t < (s + u) / 2]
b = balanced10m = [t for s, t, u in zip(p, p[1:], p[2:]) 
                   if t == (s + u) / 2]

print('The first   36   strong primes:', s[:36])
print('The   count   of the strong primes below   1,000,000:',
      sum(1 for p in s if p < 1_000_000))
print('The   count   of the strong primes below  10,000,000:', len(s))
print('\nThe first   37   weak primes:', w[:37])
print('The   count   of the weak   primes below   1,000,000:',
      sum(1 for p in w if p < 1_000_000))
print('The   count   of the weak   primes below  10,000,000:', len(w))
print('\n\nThe first   10 balanced primes:', b[:10])
print('The   count   of balanced   primes below   1,000,000:',
      sum(1 for p in b if p < 1_000_000))
print('The   count   of balanced   primes below  10,000,000:', len(b))
print('\nTOTAL primes below   1,000,000:',
      sum(1 for pr in p if pr < 1_000_000))
print('TOTAL primes below  10,000,000:', len(p))
Task: Strange unique prime triplets







Python: from sympy import primerange

def strange_triplets(mx: int = 30) -> None:
    primes = list(primerange(0, mx))
    primes3 = set(primerange(0, 3 * mx))
    for i, n in enumerate(primes):
        for j, m in enumerate(primes[i + 1:], i + 1):
            for p in primes[j + 1:]:
                if n + m + p in primes3:
                    yield n, m, p

for c, (n, m, p) in enumerate(strange_triplets(), 1):
    print(f"{c:2}: {n:2}+{m:2}+{p:2} = {n + m + p}")

mx = 1_000
print(f"\nIf n, m, p < {mx:_} finds {sum(1 for _ in strange_triplets(mx)):_}")
Task: Motzkin numbers







Python: 

from sympy import isprime


def motzkin(num_wanted):
    
    mot = [1] * (num_wanted + 1)
    for i in range(2, num_wanted + 1):
        mot[i] = (mot[i-1]*(2*i+1) + mot[i-2]*(3*i-3)) // (i + 2)
    return mot


def print_motzkin_table(N=41):
    
    print(
        " n          M[n]             Prime?\n-----------------------------------")
    for i, e in enumerate(motzkin(N)):
        print(f'{i : 3}{e : 24,}', isprime(e))


print_motzkin_table()
Task: Special neighbor primes







Python: 

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

def nextPrime(n):
    
    if n == 0:
        return 2
    if n < 3:
        return n + 1
    q = n + 2
    while not isPrime(q):
        q += 2
    return q


if __name__ == "__main__":
    for p1 in range(3,100,2):
        p2 = nextPrime(p1)
        if isPrime(p1) and p2 < 100 and isPrime(p1 + p2 - 1):
            print(p1,'\t', p2,'\t', p1 + p2 - 1)
Task: Strange plus numbers







Python: Python 3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from sympy import isprime

>>> [x for x in range(101,500) 
 if isprime(sum(int(c) for c in str(x)[:2])) and
    isprime(sum(int(c) for c in str(x)[1:]))]
[111, 112, 114, 116, 120, 121, 123, 125, 129, 141, 143, 147, 149, 161, 165, 167, 202, 203, 205, 207, 211, 212, 214, 216, 230, 232, 234, 238, 250, 252, 256, 258, 292, 294, 298, 302, 303, 305, 307, 320, 321, 323, 325, 329, 341, 343, 347, 349, 383, 385, 389, 411, 412, 414, 416, 430, 432, 434, 438, 470, 474, 476, 492, 494, 498]
>>>
Task: Smarandache prime-digital sequence







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 digit_check(n):
    if len(str(n))<2:
        return True
    else:
        for digit in str(n):
            if not is_prime(int(digit)):
                return False
        return True


def sequence(max_n=None):
    ii = 0
    n = 0
    while True:
        ii += 1
        if is_prime(ii):
            if max_n is not None:
                if n>max_n:
                    break
            if digit_check(ii):
                n += 1
                yield ii


if __name__ == '__main__':
    generator = sequence(100)
    for index, item in zip(range(1, 16), generator):
        print(index, item)
    for index, item in zip(range(16, 100), generator):
        pass
    print(100, generator.__next__())
Task: Square-free integers







Python: import math

def SquareFree ( _number ) :
	max = (int) (math.sqrt ( _number ))

	for root in range ( 2, max+1 ):					
		if 0 == _number % ( root * root ):
			return False

	return True

def ListSquareFrees( _start, _end ):
	count = 0
	for i in range ( _start, _end+1 ):
		if True == SquareFree( i ):
			print ( "{}\t".format(i), end="" )
			count += 1

	print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))

ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
Task: Self numbers







Python: class DigitSumer :
    def __init__(self): 
        sumdigit = lambda n : sum( map( int,str( n )))
        self.t = [sumdigit( i ) for i in xrange( 10000 )]
    def __call__ ( self,n ):
        r = 0
        while n >= 10000 :
            n,q = divmod( n,10000 )
            r += self.t[q]
        return r + self.t[n] 


def self_numbers ():
    d = DigitSumer()
    s = set([])
    i = 1
    while 1 :
        n = i + d( i )
        if i in s :
            s.discard( i )
        else:
            yield i
        s.add( n )
        i += 1

import time
p = 100
t = time.time()
for i,s in enumerate( self_numbers(),1 ):
    if i <= 50 : 
        print s,
        if i == 50 : print
    if i == p :
        print '%7.1f sec  %9dth = %d'%( time.time()-t,i,s )
        p *= 10
Task: Increasing gaps between consecutive Niven numbers







Python: 





def digit_sum(n, sum):
    sum += 1
    while n > 0 and n % 10 == 0:
        sum -= 9
        n /= 10
    
    return sum
    
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
 
print("Gap index  Gap    Niven index    Niven number")

niven = 1

while gap_index <= 22:
    sum = digit_sum(niven, sum)
    if niven % sum == 0:
        if niven > previous + gap:
            gap = niven - previous;
            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))
            gap_index += 1
        previous = niven
        niven_index += 1
    niven += 1