WeixiangYan/CodeTransOcean huggingface dataset:
Task: Rate counter

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



struct rate_state_s
{
    time_t lastFlush;
    time_t period;
    size_t tickCount;
};

void tic_rate(struct rate_state_s* pRate)
{
    pRate->tickCount += 1;

    time_t now = time(NULL);

    if((now - pRate->lastFlush) >= pRate->period)
    {
        
        size_t tps = 0.0;
        if(pRate->tickCount > 0)
            tps = pRate->tickCount / (now - pRate->lastFlush);

        printf("%u tics per second.\n", tps);

        
        pRate->tickCount = 0;
        pRate->lastFlush = now;
    }
}



void something_we_do()
{
    
    
    
    
    
    
    
    volatile size_t anchor = 0;
    size_t x = 0;
    for(x = 0; x < 0xffff; ++x)
    {
        anchor = x;
    }
}

int main()
{
    time_t start = time(NULL);

    struct rate_state_s rateWatch;
    rateWatch.lastFlush = start;
    rateWatch.tickCount = 0;
    rateWatch.period = 5; 

    time_t latest = start;
    
    for(latest = start; (latest - start) < 20; latest = time(NULL))
    {
        
        something_we_do();

        
        tic_rate(&rateWatch);
    }

    return 0;
}







Python: import subprocess
import time

class Tlogger(object):
    def __init__(self):
        self.counts = 0
        self.tottime = 0.0
        self.laststart = 0.0
        self.lastreport = time.time()

    def logstart(self):
        self.laststart = time.time()

    def logend(self):
        self.counts +=1
        self.tottime += (time.time()-self.laststart)
        if (time.time()-self.lastreport)>5.0:   
           self.report()

    def report(self):
        if ( self.counts > 4*self.tottime):
            print "Subtask execution rate: %f times/second"% (self.counts/self.tottime);
        else:
            print "Average execution time: %f seconds"%(self.tottime/self.counts);
        self.lastreport = time.time()


def taskTimer( n, subproc_args ):
    logger = Tlogger()

    for x in range(n):
        logger.logstart()
        p = subprocess.Popen(subproc_args)
        p.wait()
        logger.logend()
    logger.report()


import timeit
import sys

def main( ):

    
    s = 
    timer = timeit.Timer(s)
    rzlts = timer.repeat(5, 5000)
    for t in rzlts:
        print "Time for 5000 executions of statement = ",t
    
    
    print "
    print "Command:",sys.argv[2:]
    print ""
    for k in range(3):
       taskTimer( int(sys.argv[1]), sys.argv[2:])

main()
Task: Sequence_ smallest number greater than previous term with exactly n divisors

C: #include <stdio.h>

#define MAX 15

int count_divisors(int n) {
    int i, count = 0;
    for (i = 1; i * i <= n; ++i) {
        if (!(n % i)) {
            if (i == n / i)
                count++;
            else
                count += 2;
        }
    }
    return count;
}

int main() {
    int i, next = 1;
    printf("The first %d terms of the sequence are:\n", MAX);
    for (i = 1; next <= MAX; ++i) {
        if (next == count_divisors(i)) {           
            printf("%d ", i);
            next++;
        }
    }
    printf("\n");
    return 0;
}







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 sequence(max_n=None):
    previous = 0
    n = 0
    while True:
        n += 1
        ii = previous
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                previous = ii
                break


if __name__ == '__main__':
    for item in sequence(15):
        print(item)
Task: Pythagoras tree

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

typedef struct{
	double x,y;
}point;

void pythagorasTree(point a,point b,int times){
	
	point c,d,e;
	
	c.x = b.x - (a.y -  b.y);
	c.y = b.y - (b.x - a.x);
	
	d.x = a.x - (a.y -  b.y);
	d.y = a.y - (b.x - a.x);
	
	e.x = d.x +  ( b.x - a.x - (a.y -  b.y) ) / 2;
	e.y = d.y -  ( b.x - a.x + a.y -  b.y ) / 2;
	
	if(times>0){
		setcolor(rand()%15 + 1);
		
		line(a.x,a.y,b.x,b.y);
		line(c.x,c.y,b.x,b.y);
		line(c.x,c.y,d.x,d.y);
		line(a.x,a.y,d.x,d.y);
		
		pythagorasTree(d,e,times-1);
		pythagorasTree(e,c,times-1);
	}
}

int main(){
	
	point a,b;
	double side;
	int iter;
	
	time_t t;
	
	printf("Enter initial side length : ");
	scanf("%lf",&side);
	
	printf("Enter number of iterations : ");
	scanf("%d",&iter);
	
	a.x = 6*side/2 - side/2;
	a.y = 4*side;
	b.x = 6*side/2 + side/2;
	b.y = 4*side;
	
	initwindow(6*side,4*side,"Pythagoras Tree ?");
	
	srand((unsigned)time(&t));
	
	pythagorasTree(a,b,iter);
	
	getch();
	
	closegraph();
	
	return 0;

}







Python: def setup():
    size(800, 400)
    background(255)
    stroke(0, 255, 0)
    tree(width / 2.3, height, width / 1.8, height, 10)


def tree(x1, y1, x2, y2, depth):
    if depth <= 0: return
    dx = (x2 - x1)
    dy = (y1 - y2)

    x3 = (x2 - dy)
    y3 = (y2 - dx)
    x4 = (x1 - dy)
    y4 = (y1 - dx)
    x5 = (x4 + 0.5 * (dx - dy))
    y5 = (y4 - 0.5 * (dx + dy))

    
    beginShape()
    fill(0.0, 255.0 / depth, 0.0)
    vertex(x1, y1)
    vertex(x2, y2)
    vertex(x3, y3)
    vertex(x4, y4)
    vertex(x1, y1)
    endShape()

    
    beginShape()
    fill(0.0, 255.0 / depth, 0.0)
    vertex(x3, y3)
    vertex(x4, y4)
    vertex(x5, y5)
    vertex(x3, y3)
    endShape()

    tree(x4, y4, x5, y5, depth - 1)
    tree(x5, y5, x3, y3, depth - 1)
Task: Odd word problem

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

static int 
owp(int odd)
{
        int ch, ret;
        ch = getc(stdin);
        if (!odd) {
                putc(ch, stdout);
                if (ch == EOF || ch == '.')
                        return EOF;
                if (ispunct(ch))
                        return 0;
                owp(odd);
                return 0;
        } else {
                if (ispunct(ch))
                        return ch; 
                ret = owp(odd);
                putc(ch, stdout);
                return ret;
        }
}

int
main(int argc, char **argv)
{
        int ch = 1;
        while ((ch = owp(!ch)) != EOF) {
                if (ch)
                        putc(ch, stdout);
                if (ch == '.')
                        break;
        }
        return 0;
}







Python: from sys import stdin, stdout

def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)

def odd(prev = lambda: None):
	a = char_in()
	if not a.isalpha():
		prev()
		char_out(a)
		return a != '.'

	
	def clos():
		char_out(a)
		prev()

	return odd(clos)

def even():
	while True:
		c = char_in()
		char_out(c)
		if not c.isalpha(): return c != '.'

e = False
while odd() if e else even():
	e = not e
Task: Pseudo-random numbers_Combined recursive generator MRG32k3a

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

int64_t mod(int64_t x, int64_t y) {
    int64_t m = x % y;
    if (m < 0) {
        if (y < 0) {
            return m - y;
        } else {
            return m + y;
        }
    }
    return m;
}



const static int64_t a1[3] = { 0, 1403580, -810728 };
const static int64_t m1 = (1LL << 32) - 209;

const static int64_t a2[3] = { 527612, 0, -1370589 };
const static int64_t m2 = (1LL << 32) - 22853;

const static int64_t d = (1LL << 32) - 209 + 1; 


static int64_t x1[3];

static int64_t x2[3];

void seed(int64_t seed_state) {
    x1[0] = seed_state;
    x1[1] = 0;
    x1[2] = 0;

    x2[0] = seed_state;
    x2[1] = 0;
    x2[2] = 0;
}

int64_t next_int() {
    int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1);
    int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2);
    int64_t z = mod(x1i - x2i, m1);

    
    x1[2] = x1[1];
    x1[1] = x1[0];
    x1[0] = x1i;

    
    x2[2] = x2[1];
    x2[1] = x2[0];
    x2[0] = x2i;

    return z + 1;
}

double next_float() {
    return (double)next_int() / d;
}

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

    seed(1234567);
    printf("%lld\n", next_int());
    printf("%lld\n", next_int());
    printf("%lld\n", next_int());
    printf("%lld\n", next_int());
    printf("%lld\n", next_int());
    printf("\n");

    seed(987654321);
    for (i = 0; i < 100000; i++) {
        int64_t value = floor(next_float() * 5);
        counts[value]++;
    }
    for (i = 0; i < 5; i++) {
        printf("%d: %d\n", i, counts[i]);
    }

    return 0;
}







Python: 
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209

a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853

d = m1 + 1

class MRG32k3a():
    
    def __init__(self, seed_state=123):
        self.seed(seed_state)
    
    def seed(self, seed_state):
        assert 0 <seed_state < d, f"Out of Range 0 x < {d}"
        self.x1 = [seed_state, 0, 0]
        self.x2 = [seed_state, 0, 0]
        
    def next_int(self):
        "return random int in range 0..d"
        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1
        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2
        self.x1 = [x1i] + self.x1[:2]
        self.x2 = [x2i] + self.x2[:2]

        z = (x1i - x2i) % m1
        answer = (z + 1)
        
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / d
    

if __name__ == '__main__':
    random_gen = MRG32k3a()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    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: Biorhythms

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

int day(int y, int m, int d) {
    return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530;
}

void cycle(int diff, int l, char *t) {
    int p = round(100 * sin(2 * M_PI * diff / l));
    printf("%12s cycle: %3i%%", t, p);
    if (abs(p) < 15)
        printf(" (critical day)");
    printf("\n");
}

int main(int argc, char *argv[]) {
    int diff;

    if (argc < 7) {
        printf("Usage:\n");
        printf("cbio y1 m1 d1 y2 m2 d2\n");
        exit(1);
    }
    diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]))
             - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6])));
    printf("Age: %u days\n", diff);
    cycle(diff, 23, "Physical");
    cycle(diff, 28, "Emotional");
    cycle(diff, 33, "Intellectual");
}







Python: 

from datetime import date, timedelta
from math import floor, sin, pi

def biorhythms(birthdate,targetdate):
    
    
    
    
    print("Born: "+birthdate+" Target: "+targetdate)    
    
    
    
    birthdate = date.fromisoformat(birthdate)
    targetdate = date.fromisoformat(targetdate)
    
    
    
    days = (targetdate - birthdate).days
    
    print("Day: "+str(days))
    
    
    
    cycle_labels = ["Physical", "Emotional", "Mental"]
    cycle_lengths = [23, 28, 33]
    quadrants = [("up and rising", "peak"), ("up but falling", "transition"),
                   ("down and falling", "valley"), ("down but rising", "transition")]
    
    for i in range(3):
        label = cycle_labels[i]
        length = cycle_lengths[i]
        position = days % length
        quadrant = int(floor((4 * position) / length))
        percentage = int(round(100 * sin(2 * pi * position / length),0))
        transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position)
        trend, next = quadrants[quadrant]
        
        if percentage > 95:
            description = "peak"
        elif percentage < -95:
             description = "valley"
        elif abs(percentage) < 5:
             description = "critical transition"
        else:
             description = str(percentage)+"% ("+trend+", next "+next+" "+str(transition_date)+")"
        print(label+" day "+str(position)+": "+description)
    
    
biorhythms("1943-03-09","1972-07-11")
Task: Table creation_Postal addresses

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

const char *code = 
"CREATE TABLE address (\n"
"       addrID		INTEGER PRIMARY KEY AUTOINCREMENT,\n"
"	addrStreet	TEXT NOT NULL,\n"
"	addrCity	TEXT NOT NULL,\n"
"	addrState	TEXT NOT NULL,\n"
"	addrZIP		TEXT NOT NULL)\n" ;

int main()
{
  sqlite3 *db = NULL;
  char *errmsg;
  
  if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {
      fprintf(stderr, errmsg);
      sqlite3_free(errmsg);
      sqlite3_close(db);
      exit(EXIT_FAILURE);
    }
    sqlite3_close(db);
  } else {
    fprintf(stderr, "cannot open db...\n");
    sqlite3_close(db);
    exit(EXIT_FAILURE);
  }
  return EXIT_SUCCESS;
}







Python: >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute()
<sqlite3.Cursor object at 0x013265C0>
>>>
Task: Sine wave

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


int header[] = {46, 115, 110, 100, 0, 0, 0, 24,
                255, 255, 255, 255, 0, 0, 0, 3,
                0, 0, 172, 68, 0, 0, 0, 1};

int main(int argc, char *argv[]){
        float freq, dur;
        long i, v;

        if (argc < 3) {
                printf("Usage:\n");
                printf("  csine <frequency> <duration>\n");
                exit(1);
        }
        freq = atof(argv[1]);
        dur = atof(argv[2]);
        for (i = 0; i < 24; i++)
                putchar(header[i]);
        for (i = 0; i < dur * 44100; i++) {
                v = (long) round(32000. * sin(2. * M_PI * freq * i / 44100.));
                v = v % 65536;
                putchar(v >> 8);
                putchar(v % 256);
        }
}







Python: 

import os
from math import pi, sin


au_header = bytearray(
            [46, 115, 110, 100,   
              0,   0,   0,  24,   
            255, 255, 255, 255,   
              0,   0,   0,   3,   
              0,   0, 172,  68,   
              0,   0,   0,   1])  

def f(x, freq):
    "Compute sine wave as 16-bit integer"
    return round(32000 * sin(2 * pi * freq * x / 44100)) % 65536

def play_sine(freq=440, duration=5, oname="pysine.au"):
    "Play a sine wave for `duration` seconds"
    out = open(oname, 'wb')
    out.write(au_header)
    v = [f(x, freq) for x in range(duration * 44100 + 1)]
    s = []
    for i in v:
        s.append(i >> 8)
        s.append(i % 256)
    out.write(bytearray(s))
    out.close()
    os.system("vlc " + oname)   

play_sine()
Task: Compiler_code generator

C: count = 1;
while (count < 10) {
    print("count is: ", count, "\n");
    count = count + 1;
}







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: Stern-Brocot sequence

C:     k=2; i=1; j=2;
    while(k<nn);
        k++; sb[k]=sb[k-i]+sb[k-j];
        k++; sb[k]=sb[k-j];
        i++; j++;
    }







Python: def stern_brocot(predicate=lambda series: len(series) < 20):
    

    sb, i = [1, 1], 0
    while predicate(sb):
        sb += [sum(sb[i:i + 2]), sb[i + 1]]
        i += 1
    return sb


if __name__ == '__main__':
    from fractions import gcd

    n_first = 15
    print('The first %i values:\n  ' % n_first,
          stern_brocot(lambda series: len(series) < n_first)[:n_first])
    print()
    n_max = 10
    for n_occur in list(range(1, n_max + 1)) + [100]:
        print('1-based index of the first occurrence of %3i in the series:' % n_occur,
              stern_brocot(lambda series: n_occur not in series).index(n_occur) + 1)
              
              

    print()
    n_gcd = 1000
    s = stern_brocot(lambda series: len(series) < n_gcd)[:n_gcd]
    assert all(gcd(prev, this) == 1
               for prev, this in zip(s, s[1:])), 'A fraction from adjacent terms is reducible'
Task: Soundex

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


static char code[128] = { 0 };
void add_code(const char *s, int c)
{
	while (*s) {
		code[(int)*s] = code[0x20 ^ (int)*s] = c;
		s++;
	}
}

void init()
{
	static const char *cls[] =
		{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
	int i;
	for (i = 0; cls[i]; i++)
		add_code(cls[i], i - 1);
}


const char* soundex(const char *s)
{
	static char out[5];
	int c, prev, i;

	out[0] = out[4] = 0;
	if (!s || !*s) return out;

	out[0] = *s++;

	
	prev = code[(int)out[0]];
	for (i = 1; *s && i < 4; s++) {
		if ((c = code[(int)*s]) == prev) continue;

		if (c == -1) prev = 0;	
		else if (c > 0) {
			out[i++] = c + '0';
			prev = c;
		}
	}
	while (i < 4) out[i++] = '0';
	return out;
}

int main()
{
	int i;
	const char *sdx, *names[][2] = {
		{"Soundex",	"S532"},
		{"Example",	"E251"},
		{"Sownteks",	"S532"},
		{"Ekzampul",	"E251"},
		{"Euler",	"E460"},
		{"Gauss",	"G200"},
		{"Hilbert",	"H416"},
		{"Knuth",	"K530"},
		{"Lloyd",	"L300"},
		{"Lukasiewicz",	"L222"},
		{"Ellery",	"E460"},
		{"Ghosh",	"G200"},
		{"Heilbronn",	"H416"},
		{"Kant",	"K530"},
		{"Ladd",	"L300"},
		{"Lissajous",	"L222"},
		{"Wheaton",	"W350"},
		{"Burroughs",	"B620"},
		{"Burrows",	"B620"},
		{"O'Hara",	"O600"},
		{"Washington",	"W252"},
		{"Lee",		"L000"},
		{"Gutierrez",	"G362"},
		{"Pfister",	"P236"},
		{"Jackson",	"J250"},
		{"Tymczak",	"T522"},
		{"VanDeusen",	"V532"},
		{"Ashcraft",	"A261"},
		{0, 0}
	};

	init();

	puts("  Test name  Code  Got\n----------------------");
	for (i = 0; names[i][0]; i++) {
		sdx = soundex(names[i][0]);
		printf("%11s  %s  %s ", names[i][0], names[i][1], sdx);
		printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
	}

	return 0;
}







Python: from itertools import groupby

def soundex(word):
   codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r")
   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
   cmap2 = lambda kar: soundDict.get(kar, '9')
   sdx =  ''.join(cmap2(kar) for kar in word.lower())
   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
   sdx3 = sdx2[0:4].ljust(4,'0')
   return sdx3
Task: List rooted trees

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

typedef unsigned int uint;
typedef unsigned long long tree;
#define B(x) (1ULL<<(x))

tree *list = 0;
uint cap = 0, len = 0;
uint offset[32] = {0, 1, 0};

void append(tree t)
{
	if (len == cap) {
		cap = cap ? cap*2 : 2;
		list = realloc(list, cap*sizeof(tree));
	}
	list[len++] = 1 | t<<1;
}

void show(tree t, uint len)
{
	for (; len--; t >>= 1)
		putchar(t&1 ? '(' : ')');
}

void listtrees(uint n)
{
	uint i;
	for (i = offset[n]; i < offset[n+1]; i++) {
		show(list[i], n*2);
		putchar('\n');
	}
}


void assemble(uint n, tree t, uint sl, uint pos, uint rem)
{
	if (!rem) {
		append(t);
		return;
	}

	if (sl > rem) 
		pos = offset[sl = rem];
	else if (pos >= offset[sl + 1]) {
		
		if (!--sl) return;
		pos = offset[sl];
	}

	assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl);
	assemble(n, t, sl, pos + 1, rem);
}

void mktrees(uint n)
{
	if (offset[n + 1]) return;
	if (n) mktrees(n - 1);

	assemble(n, 0, n-1, offset[n-1], n-1);
	offset[n+1] = len;
}

int main(int c, char**v)
{
	int n;
	if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5;

	
	append(0);

	mktrees((uint)n);
	fprintf(stderr, "Number of %d-trees: %u\n", n, offset[n+1] - offset[n]);
	listtrees((uint)n);

	return 0;
}







Python: def bags(n,cache={}):
	if not n: return [(0, "")]

	upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
	return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]

def bagchain(x, n, bb, start=0):
	if not n: return [x]

	out = []
	for i in range(start, len(bb)):
		c,s = bb[i]
		if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
	return out


def replace_brackets(s):
	depth,out = 0,[]
	for c in s:
		if c == '(':
			out.append("([{"[depth%3])
			depth += 1
		else:
			depth -= 1
			out.append(")]}"[depth%3])
	return "".join(out)

for x in bags(5): print(replace_brackets(x[1]))
Task: Documentation

C: 
int add(int a, int b) {
    return a + b;
}







Python: class Doc(object):
   
   def method(self, num):
      
      pass
Task: Table creation

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

int main()
{
  sqlite3 *db = NULL;
  char *errmsg;
  
	const char *code = 
	"CREATE TABLE employee (\n"
	"    empID		INTEGER PRIMARY KEY AUTOINCREMENT,\n"
	"	firstName	TEXT NOT NULL,\n"
	"	lastName	TEXT NOT NULL,\n"
	"	AGE			INTEGER NOT NULL,\n"
	"	DOB			DATE NOT NULL)\n" ; 
	
  if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
    sqlite3_exec(db, code, NULL, NULL,  &errmsg);
    sqlite3_close(db);
  } else {
    fprintf(stderr, "cannot open db...\n");
    sqlite3_close(db);
    exit(EXIT_FAILURE);
  }
  return 0;
}







Python: >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> 
c.execute()

<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
	c.execute('insert into stocks values (?,?,?,?,?)', t)

	
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
>>> 
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
<sqlite3.Cursor object at 0x01326530>
>>> for row in c:
	print row

	
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>>
Task: Append numbers at same position in strings

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

int main(void) {
    int list[3][9], i;
    for(i=0;i<27;i++) list[i/9][i%9]=1+i;
    for(i=0;i<9;i++) printf( "%d%d%d  ", list[0][i], list[1][i], list[2][i] );
    return 0;
}







Python: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]

print([
    ''.join(str(n) for n in z) for z
    in zip(list1, list2, list3)
])
Task: Idiomatically determine all the lowercase and uppercase letters

C: #include <stdio.h>

int main(int argc, char const *argv[]) {
  for (char c = 0x41; c < 0x5b; c ++) putchar(c);
  putchar('\n');
  for (char c = 0x61; c < 0x7b; c ++) putchar(c);
  putchar('\n');
  return 0;
}







Python: classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
           str.isspace, str.istitle)

for stringclass in classes:
    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
    print('\nString class %s has %i characters the first of which are:\n  %r'
          % (stringclass.__name__, len(chars), chars[:100]))
Task: Sum of elements below main diagonal of matrix

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

typedef struct{
	int rows,cols;
	int** dataSet;
}matrix;

matrix readMatrix(char* dataFile){
	FILE* fp = fopen(dataFile,"r");
	matrix rosetta;
	int i,j;
	
	fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
	
	rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
	
	for(i=0;i<rosetta.rows;i++){
		rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
		for(j=0;j<rosetta.cols;j++)
			fscanf(fp,"%d",&rosetta.dataSet[i][j]);
	}
	
	fclose(fp);
	return rosetta;
}

void printMatrix(matrix rosetta){
	int i,j;
	
	for(i=0;i<rosetta.rows;i++){
		printf("\n");
		for(j=0;j<rosetta.cols;j++)
			printf("%3d",rosetta.dataSet[i][j]);
	}
}

int findSum(matrix rosetta){
	int i,j,sum = 0;
	
	for(i=1;i<rosetta.rows;i++){
		for(j=0;j<i;j++){
			sum += rosetta.dataSet[i][j];
		}
	}
	
	return sum;
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		return printf("Usage : %s <filename>",argV[0]);
	
	matrix data = readMatrix(argV[1]);
	
	printf("\n\nMatrix is : \n\n");
	printMatrix(data);
	
	printf("\n\nSum below main diagonal : %d",findSum(data));
	
	return 0;
}







Python: from numpy import array, tril, sum

A = [[1,3,7,8,10],
    [2,4,16,14,4],
    [3,1,9,18,11],
    [12,14,17,18,20],
    [7,1,3,9,5]]

print(sum(tril(A, -1)))