WeixiangYan/CodeTransOcean huggingface dataset:
Task: Minimum numbers of three lists

C: #include <stdio.h>

int min(int a, int b) {
    if (a < b) return a;
    return b;
}

int main() {
    int n;
    int numbers1[5] = {5, 45, 23, 21, 67};
    int numbers2[5] = {43, 22, 78, 46, 38};
    int numbers3[5] = {9, 98, 12, 98, 53};
    int numbers[5]  = {};
    for (n = 0; n < 5; ++n) {
        numbers[n] = min(min(numbers1[n], numbers2[n]), numbers3[n]);
        printf("%d ", numbers[n]);
    }
    printf("\n");
    return 0;
}







Python: numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]

numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]

print(numbers)
Task: Pseudo-random numbers_PCG32

C: #include <math.h>
#include <stdint.h>
#include <stdio.h>

const uint64_t N = 6364136223846793005;

static uint64_t state = 0x853c49e6748fea9b;
static uint64_t inc = 0xda3e39cb94b95bdb;

uint32_t pcg32_int() {
    uint64_t old = state;
    state = old * N + inc;
    uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
    uint32_t rot = old >> 59;
    return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
}

double pcg32_float() {
    return ((double)pcg32_int()) / (1LL << 32);
}

void pcg32_seed(uint64_t seed_state, uint64_t seed_sequence) {
    state = 0;
    inc = (seed_sequence << 1) | 1;
    pcg32_int();
    state = state + seed_state;
    pcg32_int();
}

int main() {
    int counts[5] = { 0, 0, 0, 0, 0 };
    int i;

    pcg32_seed(42, 54);
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("%u\n", pcg32_int());
    printf("\n");

    pcg32_seed(987654321, 1);
    for (i = 0; i < 100000; i++) {
        int j = (int)floor(pcg32_float() * 5.0);
        counts[j]++;
    }

    printf("The counts for 100,000 repetitions are:\n");
    for (i = 0; i < 5; i++) {
        printf("  %d : %d\n", i, counts[i]);
    }

    return 0;
}







Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005


class PCG32():
    
    def __init__(self, seed_state=None, seed_sequence=None):
        if all(type(x) == int for x in (seed_state, seed_sequence)):
            self.seed(seed_state, seed_sequence)
        else:
            self.state = self.inc = 0
    
    def seed(self, seed_state, seed_sequence):
        self.state = 0
        self.inc = ((seed_sequence << 1) | 1) & mask64
        self.next_int()
        self.state = (self.state + seed_state)
        self.next_int()
        
    def next_int(self):
        "return random 32 bit unsigned int"
        old = self.state
        self.state = ((old * CONST) + self.inc) & mask64
        xorshifted = (((old >> 18) ^ old) >> 27) & mask32
        rot = (old >> 59) & mask32
        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
        answer = answer &mask32
        
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = PCG32()
    random_gen.seed(42, 54)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321, 1)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Bitmap_PPM conversion through a pipe

C: 
void print_jpg(image img, int qual);







Python: 

from PIL import Image

im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
Task: Bitcoin_public point to address

C: #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/sha.h>
#include <openssl/ripemd.h>

#define COIN_VER 0
const char *coin_err;

typedef unsigned char byte;

int is_hex(const char *s) {
	int i;
	for (i = 0; i < 64; i++)
		if (!isxdigit(s[i])) return 0;
	return 1;
}

void str_to_byte(const char *src, byte *dst, int n) {
	while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}

char* base58(byte *s, char *out) {
	static const char *tmpl = "123456789"
		"ABCDEFGHJKLMNPQRSTUVWXYZ"
		"abcdefghijkmnopqrstuvwxyz";
	static char buf[40];

	int c, i, n;
	if (!out) out = buf;

	out[n = 34] = 0;
	while (n--) {
		for (c = i = 0; i < 25; i++) {
			c = c * 256 + s[i];
			s[i] = c / 58;
			c %= 58;
		}
		out[n] = tmpl[c];
	}

	for (n = 0; out[n] == '1'; n++);
	memmove(out, out + n, 34 - n);

	return out;
}

char *coin_encode(const char *x, const char *y, char *out) {
	byte s[65];
	byte rmd[5 + RIPEMD160_DIGEST_LENGTH];

	if (!is_hex(x) || !(is_hex(y))) {
		coin_err = "bad public point string";
		return 0;
	}

	s[0] = 4;
	str_to_byte(x, s + 1, 32);
	str_to_byte(y, s + 33, 32);

	rmd[0] = COIN_VER;
	RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1);

	memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4);

	return base58(rmd, out);
}

int main(void) {
	puts(coin_encode(
		"50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352",
		"2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6",
		0));
	return 0;
}







Python: 

import binascii
import functools
import hashlib

digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'

def b58(n):
    return b58(n//58) + digits58[n%58:n%58+1] if n else b''

def public_point_to_address(x, y):
    c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y)
    r = hashlib.new('ripemd160')
    r.update(hashlib.sha256(c).digest())
    c = b'\x00' + r.digest()
    d = hashlib.sha256(hashlib.sha256(c).digest()).digest()
    return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4]))

if __name__ == '__main__':
    print(public_point_to_address(
        b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352',
        b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
Task: Disarium numbers

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>

int power (int base, int exponent) {
    int result = 1;
    for (int i = 1; i <= exponent; i++) {
        result *= base;
    }
    return result;
}

int is_disarium (int num) {
    int n = num;
    int sum = 0;
    int len = n <= 9 ? 1 : floor(log10(n)) + 1;
    while (n > 0) {
        sum += power(n % 10, len);
        n /= 10;
        len--;
    }

    return num == sum;
}

int main() {
    int count = 0;
    int i = 0;
    while (count < 19) {
        if (is_disarium(i)) {
            printf("%d ", i);
            count++;
        }
        i++;
    }
    printf("%s\n", "\n");
}







Python: 

def isDisarium(n):
    digitos = len(str(n))
    suma = 0
    x = n
    while x != 0:
        suma += (x % 10) ** digitos
        digitos -= 1
        x //= 10
    if suma == n:
        return True
    else:
        return False

if __name__ == '__main__':
    limite = 19
    cont = 0
    n = 0
    print("The first",limite,"Disarium numbers are:")
    while cont < limite:
        if isDisarium(n):
            print(n, end = " ")
            cont += 1
        n += 1
Task: Sierpinski pentagon

C: #include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>

#define pi M_PI

int main(){
	
	time_t t;
	double side, **vertices,seedX,seedY,windowSide = 500,sumX=0,sumY=0;
	int i,iter,choice,numSides;
	
	printf("Enter number of sides : ");
	scanf("%d",&numSides);
	
	printf("Enter polygon side length : ");
	scanf("%lf",&side);
	
	printf("Enter number of iterations : ");
	scanf("%d",&iter);

	initwindow(windowSide,windowSide,"Polygon Chaos");
	
	vertices = (double**)malloc(numSides*sizeof(double*));
	
	for(i=0;i<numSides;i++){
		vertices[i] = (double*)malloc(2 * sizeof(double));
		
		vertices[i][0] = windowSide/2 + side*cos(i*2*pi/numSides);
		vertices[i][1] = windowSide/2 + side*sin(i*2*pi/numSides);
		sumX+= vertices[i][0];
		sumY+= vertices[i][1];
		putpixel(vertices[i][0],vertices[i][1],15);
	}
	
	srand((unsigned)time(&t));
	
	seedX = sumX/numSides;
	seedY = sumY/numSides;
	
	putpixel(seedX,seedY,15);
	
	for(i=0;i<iter;i++){
		choice = rand()%numSides;
		
		seedX = (seedX + (numSides-2)*vertices[choice][0])/(numSides-1);
		seedY = (seedY + (numSides-2)*vertices[choice][1])/(numSides-1);
		
		putpixel(seedX,seedY,15);
	}
	
	free(vertices);
	
	getch();
	
	closegraph();
	
	return 0;
}







Python: from turtle import *
import math
speed(0)      
hideturtle()  

part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)

hide_turtles = True   
path_color = "black"  
fill_color = "black"  


def pentagon(t, s):
  t.color(path_color, fill_color)
  t.pendown()
  t.right(36)
  t.begin_fill()
  for i in range(5):
    t.forward(s)
    t.right(72)
  t.end_fill()


def sierpinski(i, t, s):
  t.setheading(0)
  new_size = s * side_ratio
  
  if i > 1:
    i -= 1
    
    
    for j in range(4):
      t.right(36)
      short = s * side_ratio / part_ratio
      dist = [short, s, s, short][j]
      
      
      spawn = Turtle()
      if hide_turtles:spawn.hideturtle()
      spawn.penup()
      spawn.setposition(t.position())
      spawn.setheading(t.heading())
      spawn.forward(dist)
      
      
      sierpinski(i, spawn, new_size)
    
    
    sierpinski(i, t, new_size)
    
  else:
    
    pentagon(t, s)
    
    del t

def main():
  t = Turtle()
  t.hideturtle()
  t.penup()
  screen = t.getscreen()
  y = screen.window_height()
  t.goto(0, y/2-20)
  
  i = 5       
  size = 300  
  
  
  size *= part_ratio
  
  
  sierpinski(i, t, size)

main()
Task: Bitmap_Histogram

C: typedef unsigned int histogram_t;
typedef histogram_t *histogram;

#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )

histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);







Python: from PIL import Image


image = Image.open("lena.jpg")

width, height = image.size

amount = width * height


total = 0

bw_image = Image.new('L', (width, height), 0)

bm_image = Image.new('1', (width, height), 0)

for h in range(0, height):
    for w in range(0, width):
        r, g, b = image.getpixel((w, h))

        greyscale = int((r + g + b) / 3)
        total += greyscale

        bw_image.putpixel((w, h), gray_scale)


avg = total / amount

black = 0
white = 1

for h in range(0, height):
    for w in range(0, width):
        v = bw_image.getpixel((w, h))

        if v >= avg:
            bm_image.putpixel((w, h), white)
        else:
            bm_image.putpixel((w, h), black)

bw_image.show()
bm_image.show()
Task: Padovan n-step number sequences

C: #include <stdio.h>

void padovanN(int n, size_t t, int *p) {
    int i, j;
    if (n < 2 || t < 3) {
        for (i = 0; i < t; ++i) p[i] = 1;
        return;
    }
    padovanN(n-1, t, p);
    for (i = n + 1; i < t; ++i) {
        p[i] = 0;
        for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
    }
}

int main() {
    int n, i;
    const size_t t = 15;
    int p[t];
    printf("First %ld terms of the Padovan n-step number sequences:\n", t);
    for (n = 2; n <= 8; ++n) {
        for (i = 0; i < t; ++i) p[i] = 0;
        padovanN(n, t, p);
        printf("%d: ", n);
        for (i = 0; i < t; ++i) printf("%3d ", p[i]);
        printf("\n");
    }
    return 0;
}







Python: def pad_like(max_n=8, t=15):
    
    start = [[], [1, 1, 1]]     
    for n in range(2, max_n+1):
        this = start[n-1][:n+1]     
        while len(this) < t:
            this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
        start.append(this)
    return start[2:]

def pr(p):
    print(.strip())
    for n, seq in enumerate(p, 2):
        print(f"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\n|-")
    print('|}')

if __name__ == '__main__':
    p = pad_like()
    pr(p)
Task: Mutex

C: HANDLE hMutex = CreateMutex(NULL, FALSE, NULL);







Python: import threading
from time import sleep



res = 2
sema = threading.Semaphore(res)

class res_thread(threading.Thread):
    def run(self):
        global res
        n = self.getName()
        for i in range(1, 4):
            
            
            
            sema.acquire()
            res = res - 1
            print n, "+  res count", res
            sleep(2)

                        
            res = res + 1
            print n, "-  res count", res
            sema.release()


for i in range(1, 5):
    t = res_thread()
    t.start()
Task: Metronome

C: #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

struct timeval start, last;

inline int64_t tv_to_u(struct timeval s)
{
	return s.tv_sec * 1000000 + s.tv_usec;
}

inline struct timeval u_to_tv(int64_t x)
{
	struct timeval s;
	s.tv_sec = x / 1000000;
	s.tv_usec = x % 1000000;
	return s;
}

void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
	int len = 40 * (next - cur) / period;
	int s, i;

	if (len > 20) len = 40 - len;
	s = 20 + (dir ? len : -len);

	printf("\033[H");
	for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '#' : '-');
}

void beat(int delay)
{
	struct timeval tv = start;
	int dir = 0;
	int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
	int64_t draw_interval = 20000;
	printf("\033[H\033[J");
	while (1) {
		gettimeofday(&tv, 0);
		slp = next - tv_to_u(tv) - corr;
		usleep(slp);
		gettimeofday(&tv, 0);

		putchar(7); 
		fflush(stdout);

		printf("\033[5;1Hdrift: %d compensate: %d (usec)   ",
			(int)d, (int)corr);
		dir = !dir;

		cur = tv_to_u(tv);
		d = cur - next;
		corr = (corr + d) / 2;
		next += delay;

		while (cur + d + draw_interval < next) {
			usleep(draw_interval);
			gettimeofday(&tv, 0);
			cur = tv_to_u(tv);
			draw(dir, delay, cur, next);
			fflush(stdout);
		}
	}
}

int main(int c, char**v)
{
	int bpm;

	if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
	if (bpm > 600) {
		fprintf(stderr, "frequency %d too high\n", bpm);
		exit(1);
	}

	gettimeofday(&start, 0);
	last = start;
	beat(60 * 1000000 / bpm);

	return 0;
}







Python: 
import time

def main(bpm = 72, bpb = 4):
    sleep = 60.0 / bpm
    counter = 0
    while True:
        counter += 1
        if counter % bpb:
            print 'tick'
        else:
            print 'TICK'
        time.sleep(sleep)
        


main()
Task: Native shebang

C: #!/usr/local/bin/script_gcc.sh

#include <errno.h>
#include <libgen.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>




typedef char  *STRING;
typedef enum{FALSE=0, TRUE=1} BOOL;
const STRING ENDCAT = NULL;


#define DIALECT "c" 
const STRING
  CC="gcc",
  COPTS="-lm -x "DIALECT,
  IEXT="."DIALECT,
  OEXT=".out";
const BOOL OPT_CACHE = TRUE;


char strcat_out[BUFSIZ];

STRING STRCAT(STRING argv, ... ){
  va_list ap;
  va_start(ap, argv);
  STRING arg;
  strcat_out[0]='\0';
  for(arg=argv; arg != ENDCAT; arg=va_arg(ap, STRING)){
     strncat(strcat_out, arg, sizeof strcat_out);
  }
  va_end(ap);
  return strndup(strcat_out, sizeof strcat_out);
}

char itoa_out[BUFSIZ];

STRING itoa_(int i){
  sprintf(itoa_out, "%d", i);
  return itoa_out;
}

time_t modtime(STRING filename){
  struct stat buf;
  if(stat(filename, &buf) != EXIT_SUCCESS)perror(filename);
  return buf.st_mtime;
}


BOOL compile(STRING srcpath, STRING binpath){
  int out;
  STRING compiler_command=STRCAT(CC, " ", COPTS, " -o ", binpath, " -", ENDCAT);
  FILE *src=fopen(srcpath, "r"),
       *compiler=popen(compiler_command, "w");
  char buf[BUFSIZ];
  BOOL shebang;

  for(shebang=TRUE; fgets(buf, sizeof buf, src); shebang=FALSE)
    if(!shebang)fwrite(buf, strlen(buf), 1, compiler);

  out=pclose(compiler);
  return out;
}

void main(int argc, STRING *argv, STRING *envp){

  STRING binpath,
         srcpath=argv[1],
         argv0_basename=STRCAT(basename((char*)srcpath ), ENDCAT),
         *dirnamew, *dirnamex;
  argv++; 


  STRING paths[] = {
    dirname(strdup(srcpath)), 
    STRCAT(getenv("HOME"), "/bin", ENDCAT),
    "/usr/local/bin",
    ".",
    STRCAT(getenv("HOME"), "/tmp", ENDCAT),
    getenv("HOME"),
    STRCAT(getenv("HOME"), "/Desktop", ENDCAT),

    ENDCAT
  };

  for(dirnamew = paths; *dirnamew; dirnamew++){
    if(access(*dirnamew, W_OK) == EXIT_SUCCESS) break;
  }


  if(OPT_CACHE == FALSE){
    binpath=STRCAT(*dirnamew, "/", argv0_basename, itoa_(getpid()), OEXT, ENDCAT);
    if(compile(srcpath, binpath) == EXIT_SUCCESS){
      if(fork()){
        sleep(0.1); unlink(binpath);
      } else {
        execvp(binpath, argv);
      }
    }
  } else {

    time_t modtime_srcpath = modtime(srcpath);
    for(dirnamex = paths; *dirnamex; dirnamex++){
      binpath=STRCAT(*dirnamex, "/", argv0_basename, OEXT, ENDCAT);
      if((access(binpath, X_OK) == EXIT_SUCCESS) && (modtime(binpath) >= modtime_srcpath))
        execvp(binpath, argv);
    }
  }

  binpath=STRCAT(*dirnamew, "/", argv0_basename, OEXT, ENDCAT);
  if(compile(srcpath, binpath) == EXIT_SUCCESS)
    execvp(binpath, argv);

  perror(STRCAT(binpath, ": executable not available", ENDCAT));
  exit(errno);
}







Python: 


import sys
print " ".join(sys.argv[1:])
Task: EKG sequence convergence

C: #include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0
#define LIMIT 100

typedef int bool;

int compareInts(const void *a, const void *b) {
    int aa = *(int *)a;
    int bb = *(int *)b;
    return aa - bb;
}

bool contains(int a[], int b, size_t len) {
    int i;
    for (i = 0; i < len; ++i) {
        if (a[i] == b) return TRUE;
    }
    return FALSE;
}

int gcd(int a, int b) {
    while (a != b) {
        if (a > b)
            a -= b;
        else
            b -= a;
    }
    return a;
}

bool areSame(int s[], int t[], size_t len) {
    int i;
    qsort(s, len, sizeof(int), compareInts);    
    qsort(t, len, sizeof(int), compareInts);
    for (i = 0; i < len; ++i) {
        if (s[i] != t[i]) return FALSE;
    }
    return TRUE;
}

int main() {
    int s, n, i;
    int starts[5] = {2, 5, 7, 9, 10};
    int ekg[5][LIMIT];
    for (s = 0; s < 5; ++s) {
        ekg[s][0] = 1;
        ekg[s][1] = starts[s];
        for (n = 2; n < LIMIT; ++n) {
            for (i = 2; ; ++i) {
                
                
                if (!contains(ekg[s], i, n) && gcd(ekg[s][n - 1], i) > 1) {
                    ekg[s][n] = i;
                    break;
                }
            }
        }
        printf("EKG(%2d): [", starts[s]);
        for (i = 0; i < 30; ++i) printf("%d ", ekg[s][i]);
        printf("\b]\n");
    }
    
    
    for (i = 2; i < LIMIT; ++i) {
        if (ekg[1][i] == ekg[2][i] && areSame(ekg[1], ekg[2], i)) {
            printf("\nEKG(5) and EKG(7) converge at term %d\n", i + 1);
            return 0;
        }
    }
    printf("\nEKG5(5) and EKG(7) do not converge within %d terms\n", LIMIT);
    return 0;
}







Python: from itertools import count, islice, takewhile
from math import gcd

def EKG_gen(start=2):
    
    c = count(start + 1)
    last, so_far = start, list(range(2, start))
    yield 1, []
    yield last, []
    while True:
        for index, sf in enumerate(so_far):
            if gcd(last, sf) > 1:
                last = so_far.pop(index)
                yield last, so_far[::]
                break
        else:
            so_far.append(next(c))

def find_convergence(ekgs=(5,7)):
    "Returns the convergence point or zero if not found within the limit"
    ekg = [EKG_gen(n) for n in ekgs]
    for e in ekg:
        next(e)    
    return 2 + len(list(takewhile(lambda state: not all(state[0] == s for  s in state[1:]),
                                  zip(*ekg))))

if __name__ == '__main__':
    for start in 2, 5, 7, 9, 10:
        print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1])
    print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
Task: Rep-string

C: #include <stdio.h>
#include <string.h>

int repstr(char *str)
{
    if (!str) return 0;

    size_t sl = strlen(str) / 2;
    while (sl > 0) {
        if (strstr(str, str + sl) == str)
            return sl;
        --sl;
    }

    return 0;
}

int main(void)
{
    char *strs[] = { "1001110011", "1110111011", "0010010010", "1111111111",
        "0100101101", "0100100", "101", "11", "00", "1" };

    size_t strslen = sizeof(strs) / sizeof(strs[0]);
    size_t i;
    for (i = 0; i < strslen; ++i) {
        int n = repstr(strs[i]);
        if (n)
            printf("\"%s\" = rep-string \"%.*s\"\n", strs[i], n, strs[i]);
        else
            printf("\"%s\" = not a rep-string\n", strs[i]);
    }

    return 0;
}







Python: def is_repeated(text):
    'check if the first part of the string is repeated throughout the string'
    for x in range(len(text)//2, 0, -1):
        if text.startswith(text[x:]): return x
    return 0

matchstr = 
for line in matchstr.split():
    ln = is_repeated(line)
    print('%r has a repetition length of %i i.e. %s' 
           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
Task: Terminal control_Preserve screen

C: #include <stdio.h>
#include <unistd.h>

int main()
{
	int i;
	printf("\033[?1049h\033[H");
	printf("Alternate screen buffer\n");
	for (i = 5; i; i--) {
		printf("\rgoing back in %d...", i);
		fflush(stdout);
		sleep(1);
	}
	printf("\033[?1049l");

	return 0;
}







Python: 

import time

print "\033[?1049h\033[H"
print "Alternate buffer!"

for i in xrange(5, 0, -1):
    print "Going back in:", i
    time.sleep(1)

print "\033[?1049l"
Task: Literals_String

C: char ch = 'z';







Python: 'c' == "c" 
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
Task: Monads_List monad

C: #include <stdio.h>
#include <stdlib.h>

#define MONAD void*
#define INTBIND(f, g, x) (f((int*)g(x)))
#define RETURN(type,x) &((type)*)(x)

MONAD boundInt(int *x) {
    return (MONAD)(x);
}

MONAD boundInt2str(int *x) {
    char buf[100];
    char*str= malloc(1+sprintf(buf, "%d", *x));
    sprintf(str, "%d", *x);
    return (MONAD)(str);
}

void task(int y) {
    char *z= INTBIND(boundInt2str, boundInt, &y);
    printf("%s\n", z);
    free(z);
}

int main() {
    task(13);
}







Python: 
from __future__ import annotations
from itertools import chain

from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar


T = TypeVar("T")


class MList(List[T]):
    @classmethod
    def unit(cls, value: Iterable[T]) -> MList[T]:
        return cls(value)

    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return MList(chain.from_iterable(map(func, self)))

    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return self.bind(func)


if __name__ == "__main__":
    
    print(
        MList([1, 99, 4])
        .bind(lambda val: MList([val + 1]))
        .bind(lambda val: MList([f"${val}.00"]))
    )

    
    print(
        MList([1, 99, 4])
        >> (lambda val: MList([val + 1]))
        >> (lambda val: MList([f"${val}.00"]))
    )

    
    print(
        MList(range(1, 6)).bind(
            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
        )
    )

    
    print(
        MList(range(1, 26)).bind(
            lambda x: MList(range(x + 1, 26)).bind(
                lambda y: MList(range(y + 1, 26)).bind(
                    lambda z: MList([(x, y, z)])
                    if x * x + y * y == z * z
                    else MList([])
                )
            )
        )
    )
Task: Find squares n where n+1 is prime

C: #include <stdio.h>
#include <stdbool.h>
#include <math.h>

#define MAX 1000

void sieve(int n, bool *prime) {
    prime[0] = prime[1] = false;
    for (int i=2; i<=n; i++) prime[i] = true;
    for (int p=2; p*p<=n; p++) 
        if (prime[p])
            for (int c=p*p; c<=n; c+=p) prime[c] = false;
}

bool square(int n) {
    int sq = sqrt(n);
    return (sq * sq == n);
}

int main() {
    bool prime[MAX + 1];
    sieve(MAX, prime);
    for (int i=2; i<=MAX; i++) if (prime[i]) {
        int sq = i-1;
        if (square(sq)) printf("%d ", sq);
    }
    printf("\n");
    return 0;
}







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...")