WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Pancake sort

C: int pancake_sort(int *list, unsigned int length)
{
    
    if(length<2)
        return 0;

    int i,a,max_num_pos,moves;
    moves=0;

    for(i=length;i>1;i--)
    {
        
        max_num_pos=0;
        for(a=0;a<i;a++)
        {
            if(list[a]>list[max_num_pos])
                max_num_pos=a;
        }

        if(max_num_pos==i-1)
            
            continue;


        
        if(max_num_pos)
        {
            moves++;
            do_flip(list, length, max_num_pos+1);
        }


        
        moves++;
        do_flip(list, length, i);

        

    }

    return moves;
}







Python: tutor = False

def pancakesort(data):
    if len(data) <= 1:
        return data
    if tutor: print()
    for size in range(len(data), 1, -1):
        maxindex = max(range(size), key=data.__getitem__)
        if maxindex+1 != size:
            
            if maxindex != 0:
                
                if tutor: print('With: %r doflip  %i'
                                % ( ' '.join(str(x) for x in data), maxindex+1 ))
                data[:maxindex+1] = reversed(data[:maxindex+1])
            
            if tutor: print('With: %r  doflip %i'
                                % ( ' '.join(str(x) for x in data), size ))
            data[:size] = reversed(data[:size])
    if tutor: print()
Task: Largest five adjacent number

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

#define DIGITS 1000
#define NUMSIZE 5

uint8_t randomDigit() {
    uint8_t d;
    do {d = rand() & 0xF;} while (d >= 10);
    return d;
}

int numberAt(uint8_t *d, int size) {
    int acc = 0;
    while (size--) acc = 10*acc + *d++;
    return acc;
}

int main() {
    uint8_t digits[DIGITS];
    int i, largest = 0;
    
    srand(time(NULL));
    
    for (i=0; i<DIGITS; i++) digits[i] = randomDigit();
    for (i=0; i<DIGITS-NUMSIZE; i++) {
        int here = numberAt(&digits[i], NUMSIZE);
        if (here > largest) largest = here;
    }

    printf("%d\n", largest);
    return 0;
}







Python: 

from random import seed,randint
from datetime import datetime

seed(str(datetime.now()))

largeNum = [randint(1,9)]

for i in range(1,1000):
    largeNum.append(randint(0,9))

maxNum,minNum = 0,99999

for i in range(0,994):
    num = int("".join(map(str,largeNum[i:i+5])))
    if num > maxNum:
        maxNum = num
    elif num < minNum:
        minNum = num

print("Largest 5-adjacent number found ", maxNum)
print("Smallest 5-adjacent number found ", minNum)
Task: Sum of square and cube digits of an integer are primes

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

int digit_sum(int n) {
    int sum;
    for (sum = 0; n; n /= 10) sum += n % 10;
    return sum;
}


bool prime(int n) {
    if (n<4) return n>=2;
    for (int d=2; d*d <= n; d++)
        if (n%d == 0) return false;
    return true;
}

int main() {
    for (int i=1; i<100; i++)
        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))
            printf("%d ", i);
    printf("\n");
    return 0;
}







Python: 

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

def digSum(n, b):
    s = 0
    while n:
        s += (n % b)
        n = n // b
    return s

if __name__ == '__main__':
    for n in range(11, 99):
        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):
            print(n, end = "  ")
Task: The sieve of Sundaram

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
    int nprimes =  1000000;
    int nmax =    ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));  
      
      
    int i, j, m, k; int *a;
    k = (nmax-2)/2; 
    a = (int *)calloc(k + 1, sizeof(int));
    for(i = 0; i <= k; i++)a[i] = 2*i+1; 
    for (i = 1; (i+1)*i*2 <= k; i++)
        for (j = i; j <= (k-i)/(2*i+1); j++) {
            m = i + j + 2*i*j;
            if(a[m]) a[m] = 0;
            }            
        
    for (i = 1, j = 0; i <= k; i++) 
       if (a[i]) {
           if(j%10 == 0 && j <= 100)printf("\n");
           j++; 
           if(j <= 100)printf("%3d ", a[i]);
           else if(j == nprimes){
               printf("\n%d th prime is %d\n",j,a[i]);
               break;
               }
           }
}







Python: from numpy import log

def sieve_of_Sundaram(nth, print_all=True):
    
    assert nth > 0, "nth must be a positive integer"
    k = int((2.4 * nth * log(nth)) // 2)  
    integers_list = [True] * k
    for i in range(1, k):
        j = i
        while i + j + 2 * i * j < k:
            integers_list[i + j + 2 * i * j] = False
            j += 1
    pcount = 0
    for i in range(1, k + 1):
        if integers_list[i]:
            pcount += 1
            if print_all:
                print(f"{2 * i + 1:4}", end=' ')
                if pcount % 10 == 0:
                    print()

            if pcount == nth:
                print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
                break



sieve_of_Sundaram(100, True)

sieve_of_Sundaram(1000000, False)
Task: Active Directory_Connect

C: #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);







Python: import ldap

l = ldap.initialize("ldap://ldap.example.com")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)

    bind = l.simple_bind_s("me@example.com", "password")
finally:
    l.unbind()
Task: Exactly three adjacent 3 in lists

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

bool three_3s(const int *items, size_t len) {
    int threes = 0;    
    while (len--) 
        if (*items++ == 3)
            if (threes<3) threes++;
            else return false;
        else if (threes != 0 && threes != 3) 
            return false;
    return true;
}

void print_list(const int *items, size_t len) {
    while (len--) printf("%d ", *items++);
}

int main() {
    int lists[][9] = {
        {9,3,3,3,2,1,7,8,5},
        {5,2,9,3,3,6,8,4,1},
        {1,4,3,6,7,3,8,3,2},
        {1,2,3,4,5,6,7,8,9},
        {4,6,8,7,2,3,3,3,1}
    };
    
    size_t list_length = sizeof(lists[0]) / sizeof(int);
    size_t n_lists = sizeof(lists) / sizeof(lists[0]);
    
    for (size_t i=0; i<n_lists; i++) {
        print_list(lists[i], list_length);
        printf("-> %s\n", three_3s(lists[i], list_length) ? "true" : "false");
    }
    
    return 0;
}







Python: 

from itertools import dropwhile, takewhile



def nnPeers(n):
    
    def p(x):
        return n == x

    def go(xs):
        fromFirstMatch = list(dropwhile(
            lambda v: not p(v),
            xs
        ))
        ns = list(takewhile(p, fromFirstMatch))
        rest = fromFirstMatch[len(ns):]

        return p(len(ns)) and (
            not any(p(x) for x in rest)
        )

    return go




def main():
    
    print(
        '\n'.join([
            f'{xs} -> {nnPeers(3)(xs)}' for xs in [
                [9, 3, 3, 3, 2, 1, 7, 8, 5],
                [5, 2, 9, 3, 3, 7, 8, 4, 1],
                [1, 4, 3, 6, 7, 3, 8, 3, 2],
                [1, 2, 3, 4, 5, 6, 7, 8, 9],
                [4, 6, 8, 7, 2, 3, 3, 3, 1]
            ]
        ])
    )



if __name__ == '__main__':
    main()
Task: Permutations by swapping

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

int flag = 1;

void heapPermute(int n, int arr[],int arrLen){
	int temp;
	int i;
	
	if(n==1){
		printf("\n[");
		
		for(i=0;i<arrLen;i++)
			printf("%d,",arr[i]);
		printf("\b] Sign : %d",flag);
		
		flag*=-1;
	}
	else{
		for(i=0;i<n-1;i++){
			heapPermute(n-1,arr,arrLen);
			
			if(n%2==0){
				temp = arr[i];
				arr[i] = arr[n-1];
				arr[n-1] = temp;
			}
			else{
				temp = arr[0];
				arr[0] = arr[n-1];
				arr[n-1] = temp;
			}
		}
		heapPermute(n-1,arr,arrLen);
	}
}

int main(int argC,char* argV[0])
{
	int *arr, i=0, count = 1;
	char* token;
	
	if(argC==1)
		printf("Usage : %s <comma separated list of integers>",argV[0]);
	else{
		while(argV[1][i]!=00){
			if(argV[1][i++]==',')
				count++;
		}
		
		arr = (int*)malloc(count*sizeof(int));
		
		i = 0;
		
		token = strtok(argV[1],",");
		
		while(token!=NULL){
			arr[i++] = atoi(token);
			token = strtok(NULL,",");
		}
		
		heapPermute(i,arr,count);
	}
		
	return 0;
}







Python: from operator import itemgetter
 
DEBUG = False 
 
def spermutations(n):
    
    sign = 1
    p = [[i, 0 if i == 0 else -1] 
         for i in range(n)]
 
    if DEBUG: print ' 
    yield tuple(pp[0] for pp in p), sign
 
    while any(pp[1] for pp in p): 
        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
                           key=itemgetter(1))
        sign *= -1
        if d1 == -1:
            
            i2 = i1 - 1
            p[i1], p[i2] = p[i2], p[i1]
            
            
            
            if i2 == 0 or p[i2 - 1][0] > n1:
                
                p[i2][1] = 0
        elif d1 == 1:
            
            i2 = i1 + 1
            p[i1], p[i2] = p[i2], p[i1]
            
            
            
            if i2 == n - 1 or p[i2 + 1][0] > n1:
                
                p[i2][1] = 0
        if DEBUG: print ' 
        yield tuple(pp[0] for pp in p), sign
 
        for i3, pp in enumerate(p):
            n3, d3 = pp
            if n3 > n1:
                pp[1] = 1 if i3 < i2 else -1
                if DEBUG: print ' 
 
 
if __name__ == '__main__':
    from itertools import permutations
 
    for n in (3, 4):
        print '\nPermutations and sign of %i items' % n
        sp = set()
        for i in spermutations(n):
            sp.add(i[0])
            print('Perm: %r Sign: %2i' % i)
            
        
        p = set(permutations(range(n)))
        assert sp == p, 'Two methods of generating permutations do not agree'
Task: Minimum multiple of m where digital sum equals m

C: #include <stdio.h>

unsigned digit_sum(unsigned n) {
    unsigned sum = 0;
    do { sum += n % 10; }
    while(n /= 10);
    return sum;
}

unsigned a131382(unsigned n) {
    unsigned m;
    for (m = 1; n != digit_sum(m*n); m++);
    return m;
}

int main() {
    unsigned n;
    for (n = 1; n <= 70; n++) {
        printf("%9u", a131382(n));
        if (n % 10 == 0) printf("\n");
    }
    return 0;
}







Python: 

from itertools import count, islice



def a131382():
    
    return (
        elemIndex(x)(
            productDigitSums(x)
        ) for x in count(1)
    )



def productDigitSums(n):
    
    return (digitSum(n * x) for x in count(0))




def main():
    

    print(
        table(10)([
            str(x) for x in islice(
                a131382(),
                40
            )
        ])
    )





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def digitSum(n):
    
    return sum(int(x) for x in list(str(n)))



def elemIndex(x):
    
    def go(xs):
        try:
            return next(
                i for i, v in enumerate(xs) if x == v
            )
        except StopIteration:
            return None
    return go



def table(n):
    
    def go(xs):
        w = len(xs[-1])
        return '\n'.join(
            ' '.join(row) for row in chunksOf(n)([
                s.rjust(w, ' ') for s in xs
            ])
        )
    return go



if __name__ == '__main__':
    main()
Task: Pythagorean quadruples

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

#define N 2200

int main(int argc, char **argv){
   int a,b,c,d;
   int r[N+1];
   memset(r,0,sizeof(r));	
   for(a=1; a<=N; a++){
      for(b=a; b<=N; b++){
	 int aabb;
	 if(a&1 && b&1) continue;  
	 aabb=a*a + b*b;
	 for(c=b; c<=N; c++){
	    int aabbcc=aabb + c*c;
	    d=(int)sqrt((float)aabbcc);
	    if(aabbcc == d*d && d<=N) r[d]=1;	
	 }
      }
   }
   for(a=1; a<=N; a++)
      if(!r[a]) printf("%d ",a);	
   printf("\n");
}







Python: def quad(top=2200):
    r = [False] * top
    ab = [False] * (top * 2)**2
    for a in range(1, top):
        for b in range(a, top):
            ab[a * a + b * b] = True
    s = 3
    for c in range(1, top):
        s1, s, s2 = s, s + 2, s + 2
        for d in range(c + 1, top):
            if ab[s1]:
                r[d] = True
            s1 += s2
            s2 += 2
    return [i for i, val in enumerate(r) if not val and i]
    
if __name__ == '__main__':
    n = 2200
    print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Task: Steady squares

C: #include <stdio.h>
#include <stdbool.h>
 
bool steady(int n)
{
    int mask = 1;
    for (int d = n; d != 0; d /= 10) 
        mask *= 10;
    return (n * n) % mask == n;
}
 
int main()
{
    for (int i = 1; i < 10000; i++)
        if (steady(i))
            printf("%4d^2 = %8d\n", i, i * i);
    return 0;
}







Python: print("working...")
print("Steady squares under 10.000 are:")
limit = 10000

for n in range(1,limit):
    nstr = str(n)
    nlen = len(nstr)
    square = str(pow(n,2))
    rn = square[-nlen:]
    if nstr == rn:
       print(str(n) + " " + str(square))

print("done...")
Task: Numbers in base 10 that are palindromic in bases 2, 4, and 16

C: #include <stdio.h>
#define MAXIMUM 25000

int reverse(int n, int base) {
    int r;
    for (r = 0; n; n /= base)
        r = r*base + n%base;
    return r;
}

int palindrome(int n, int base) {
    return n == reverse(n, base);
}

int main() {
    int i, c = 0;
    
    for (i = 0; i < MAXIMUM; i++) {
        if (palindrome(i, 2) &&
            palindrome(i, 4) &&
            palindrome(i, 16)) {
            printf("%5d%c", i, ++c % 12 ? ' ' : '\n');
        }
    }
    printf("\n");
    return 0;
}







Python: def reverse(n, base):
    r = 0
    while n > 0:
        r = r*base + n%base
        n = n//base
    return r
    
def palindrome(n, base):
    return n == reverse(n, base)
    
cnt = 0
for i in range(25000):
    if all(palindrome(i, base) for base in (2,4,16)):
        cnt += 1
        print("{:5}".format(i), end=" \n"[cnt % 12 == 0])

print()
Task: Long stairs

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

int main(void) {
    int trial, secs_tot=0, steps_tot=0;     
    int sbeh, slen, wiz, secs;              
    time_t t;
    srand((unsigned) time(&t));             
    printf( "Seconds    steps behind    steps ahead\n" );
    for( trial=1;trial<=10000;trial++ ) {   
        sbeh = 0; slen = 100; secs = 0;     
        while(sbeh<slen) {                  
            sbeh+=1;                        
            for(wiz=1;wiz<=5;wiz++) {       
                if(rand()%slen < sbeh)
                    sbeh+=1;                
                slen+=1;                    
            }
            secs+=1;                        
            if(trial==1&&599<secs&&secs<610)
                printf("%d        %d            %d\n", secs, sbeh, slen-sbeh );
            
        }
        secs_tot+=secs;
        steps_tot+=slen;
    }
    printf( "Average secs taken: %f\n", secs_tot/10000.0 );
    printf( "Average final length of staircase: %f\n", steps_tot/10000.0 ); 
    return 0;
}







Python: 

from numpy import mean
from random import sample

def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
    secs, behind, total = 0, start_step, start_length
    while True:
        behind += climber_steps
        behind += sum([behind > n for n in sample(range(total), add_steps)])
        total += add_steps
        secs += 1
        yield (secs, behind, total)
        

ls = gen_long_stairs(1, 100, 1, 5)

print("Seconds  Behind  Ahead\n----------------------")
while True:
    secs, pos, len = next(ls)
    if 600 <= secs < 610:
        print(secs, "     ", pos, "   ", len - pos)
    elif secs == 610:
        break

print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
    trialstairs = gen_long_stairs(1, 100, 1, 5)
    while True:
        sec, step, height = next(trialstairs)
        if step >= height:
            times.append(sec)
            heights.append(height)
            break

print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
Task: Terminal control_Positional read

C: #include <windows.h>
#include <wchar.h>

int
main()
{
	CONSOLE_SCREEN_BUFFER_INFO info;
	COORD pos;
	HANDLE conout;
	long len;
	wchar_t c;

	
	conout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE,
	    FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
	    0, NULL);
	if (conout == INVALID_HANDLE_VALUE)
		return 1;

	
	if (GetConsoleScreenBufferInfo(conout, &info) == 0)
		return 1;

	
	pos.X = info.srWindow.Left + 3;  
	pos.Y = info.srWindow.Top  + 6;  
	if (ReadConsoleOutputCharacterW(conout, &c, 1, pos, &len) == 0 ||
	    len <= 0)
		return 1;

	wprintf(L"Character at (3, 6) had been '%lc'\n", c);
	return 0;
}







Python: import curses
from random import randint



stdscr = curses.initscr()
for rows in range(10):
    line = ''.join([chr(randint(41, 90)) for i in range(10)])
    stdscr.addstr(line + '\n')


icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")


stdscr.move(irow, icol + 10)
stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n')
stdscr.getch()

curses.endwin()
Task: Pseudo-random numbers_Middle-square method

C: #include<stdio.h>
long long seed;
long long random(){
        seed = seed * seed / 1000 % 1000000;
        return seed;
}
int main(){
        seed = 675248;
        for(int i=1;i<=5;i++)
                printf("%lld\n",random());
        return 0;
}







Python: seed = 675248
def random():
    global seed
    seed = int(str(seed ** 2).zfill(12)[3:9])
    return seed
for _ in range(5):
    print(random())
Task: Image convolution

C: image filter(image img, double *K, int Ks, double, double);







Python: 
from PIL import Image, ImageFilter

if __name__=="__main__":
	im = Image.open("test.jpg")

	kernelValues = [-2,-1,0,-1,1,1,0,1,2] 
	kernel = ImageFilter.Kernel((3,3), kernelValues)

	im2 = im.filter(kernel)

	im2.show()
Task: Dice game probabilities

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

typedef uint32_t uint;
typedef uint64_t ulong;

ulong ipow(const uint x, const uint y) {
    ulong result = 1;
    for (uint i = 1; i <= y; i++)
        result *= x;
    return result;
}

uint min(const uint x, const uint y) {
    return (x < y) ? x : y;
}

void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) {
    if (n_dice == 0) {
        counts[s]++;
        return;
    }

    for (uint i = 1; i < n_sides + 1; i++)
        throw_die(n_sides, n_dice - 1, s + i, counts);
}

double beating_probability(const uint n_sides1, const uint n_dice1,
                           const uint n_sides2, const uint n_dice2) {
    const uint len1 = (n_sides1 + 1) * n_dice1;
    uint C1[len1];
    for (uint i = 0; i < len1; i++)
        C1[i] = 0;
    throw_die(n_sides1, n_dice1, 0, C1);

    const uint len2 = (n_sides2 + 1) * n_dice2;
    uint C2[len2];
    for (uint j = 0; j < len2; j++)
        C2[j] = 0;
    throw_die(n_sides2, n_dice2, 0, C2);

    const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2));

    double tot = 0;
    for (uint i = 0; i < len1; i++)
        for (uint j = 0; j < min(i, len2); j++)
            tot += (double)C1[i] * C2[j] / p12;
    return tot;
}

int main() {
    printf("%1.16f\n", beating_probability(4, 9, 6, 6));
    printf("%1.16f\n", beating_probability(10, 5, 7, 6));
    return 0;
}







Python: from itertools import product

def gen_dict(n_faces, n_dice):
    counts = [0] * ((n_faces + 1) * n_dice)
    for t in product(range(1, n_faces + 1), repeat=n_dice):
        counts[sum(t)] += 1
    return counts, n_faces ** n_dice

def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
    c1, p1 = gen_dict(n_sides1, n_dice1)
    c2, p2 = gen_dict(n_sides2, n_dice2)
    p12 = float(p1 * p2)

    return sum(p[1] * q[1] / p12
               for p, q in product(enumerate(c1), enumerate(c2))
               if p[0] > q[0])

print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)
Task: Plasma effect

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

#define pi M_PI

int main()
{
	CONSOLE_SCREEN_BUFFER_INFO info;
    int cols, rows;
	time_t t;
	int i,j;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
    cols = info.srWindow.Right - info.srWindow.Left + 1;
    rows = info.srWindow.Bottom - info.srWindow.Top + 1;
	
	HANDLE console;
	
	console = GetStdHandle(STD_OUTPUT_HANDLE);
	
	system("@clear||cls");
	
	srand((unsigned)time(&t));
	
	for(i=0;i<rows;i++)
		for(j=0;j<cols;j++){
			SetConsoleTextAttribute(console,fabs(sin(pi*(rand()%254 + 1)/255.0))*254);
			printf("%c",219);
		}
		
	getchar();
	
	return 0;
}







Python: 

pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False

def setup():
    global buffer
    size(600, 600)
    frameRate(25)
    buffer = [None] * width * height
    for x in range(width):
        for y in range(width):
            value = int(((128 + (128 * sin(x / 32.0)))
                         + (128 + (128 * cos(y / 32.0)))
                         + (128 + (128 * sin(sqrt((x * x + y * y)) / 32.0)))) / 4)
            buffer[x + y * width] = value

def draw():
    global r, g, b, rd, gd, bd
    if r > 128: rd = True
    if not rd: r += 1
    else: r-=1
    if r < 0: rd = False
    if g > 128: gd = True
    if not gd: g += 1
    else: g- = 1
    if r < 0: gd = False 
    if b > 128: bd = True
    if not bd: b += 1
    else: b- = 1
    if b < 0: bd = False
 
    for i in range(128):
          s_1 = sin(i * PI / 25)
          s_2 = sin(i * PI / 50 + PI / 4)
          pal[i] = color(r + s_1 * 128, g + s_2 * 128, b + s_1 * 128)

    loadPixels()
    for i, b in enumerate(buffer):
          pixels[i] = pal[(b + frameCount) % 127]
    updatePixels()
Task: Variables

C: int j;







Python: 
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"


example1 = "goodbye"
Task: Color quantization

C: typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
	
	uint64_t r, g, b;
	int count, heap_idx;
	oct_node kids[8], parent;
	unsigned char n_kids, kid_idx, flags, depth;
};


inline int cmp_node(oct_node a, oct_node b)
{
	if (a->n_kids < b->n_kids) return -1;
	if (a->n_kids > b->n_kids) return 1;

	int ac = a->count * (1 + a->kid_idx) >> a->depth;
	int bc = b->count * (1 + b->kid_idx) >> b->depth;
	return ac < bc ? -1 : ac > bc;
}


oct_node node_insert(oct_node root, unsigned char *pix)
{
#	define OCT_DEPTH 8
	

	unsigned char i, bit, depth = 0;
	for (bit = 1 << 7; ++depth < OCT_DEPTH; bit >>= 1) {
		i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
		if (!root->kids[i])
			root->kids[i] = node_new(i, depth, root);

		root = root->kids[i];
	}

	root->r += pix[0];
	root->g += pix[1];
	root->b += pix[2];
	root->count++;
	return root;
}


oct_node node_fold(oct_node p)
{
	if (p->n_kids) abort();
	oct_node q = p->parent;
	q->count += p->count;

	q->r += p->r;
	q->g += p->g;
	q->b += p->b;
	q->n_kids --;
	q->kids[p->kid_idx] = 0;
	return q;
}


void color_replace(oct_node root, unsigned char *pix)
{
	unsigned char i, bit;

	for (bit = 1 << 7; bit; bit >>= 1) {
		i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
		if (!root->kids[i]) break;
		root = root->kids[i];
	}

	pix[0] = root->r;
	pix[1] = root->g;
	pix[2] = root->b;
}


void color_quant(image im, int n_colors)
{
	int i;
	unsigned char *pix = im->pix;
	node_heap heap = { 0, 0, 0 };

	oct_node root = node_new(0, 0, 0), got;
	for (i = 0; i < im->w * im->h; i++, pix += 3)
		heap_add(&heap, node_insert(root, pix));

	while (heap.n > n_colors + 1)
		heap_add(&heap, node_fold(pop_heap(&heap)));

	double c;
	for (i = 1; i < heap.n; i++) {
		got = heap.buf[i];
		c = got->count;
		got->r = got->r / c + .5;
		got->g = got->g / c + .5;
		got->b = got->b / c + .5;
		printf("%2d | %3llu %3llu %3llu (%d pixels)\n",
			i, got->r, got->g, got->b, got->count);
	}

	for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3)
		color_replace(root, pix);

	node_free();
	free(heap.buf);
}







Python: from PIL import Image

if __name__=="__main__":
	im = Image.open("frog.png")
	im2 = im.quantize(16)
	im2.show()