WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sort numbers lexicographically

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

int compareStrings(const void *a, const void *b) {
    const char **aa = (const char **)a;
    const char **bb = (const char **)b;
    return strcmp(*aa, *bb);
}

void lexOrder(int n, int *ints) {
    char **strs;
    int i, first = 1, last = n, k = n, len;
    if (n < 1) {
        first = n; last = 1; k = 2 - n;
    } 
    strs = malloc(k * sizeof(char *));
    for (i = first; i <= last; ++i) {
        if (i >= 1) len = (int)log10(i) + 2;
        else if (i == 0) len = 2;
        else len = (int)log10(-i) + 3; 
        strs[i-first] = malloc(len);
        sprintf(strs[i-first], "%d", i);
    }
    qsort(strs, k, sizeof(char *), compareStrings);
    for (i = 0; i < k; ++i) {
        ints[i] = atoi(strs[i]);
        free(strs[i]);
    }
    free(strs);
}

int main() {
    int i, j, k, n,  *ints;
    int numbers[5] = {0, 5, 13, 21, -22};
    printf("In lexicographical order:\n\n");
    for (i = 0; i < 5; ++i) {
        k = n = numbers[i];
        if (k < 1) k = 2 - k;
        ints = malloc(k * sizeof(int));
        lexOrder(n, ints);
        printf("%3d: [", n);
        for (j = 0; j < k; ++j) {
            printf("%d ", ints[j]);
        }
        printf("\b]\n");
        free(ints);
    }
    return 0;
}







Python: n=13
print(sorted(range(1,n+1), key=str))
Task: Compare length of two strings

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

int cmp(const int* a, const int* b)
{
    return *b - *a; 
}

void compareAndReportStringsLength(const char* strings[], const int n)
{
    if (n > 0)
    {
        char* has_length = "has length";
        char* predicate_max = "and is the longest string";
        char* predicate_min = "and is the shortest string";
        char* predicate_ave = "and is neither the longest nor the shortest string";

        int* si = malloc(2 * n * sizeof(int));
        if (si != NULL)
        {
            for (int i = 0; i < n; i++)
            {
                si[2 * i] = strlen(strings[i]);
                si[2 * i + 1] = i;
            }
            qsort(si, n, 2 * sizeof(int), cmp);

            int max = si[0];
            int min = si[2 * (n - 1)];

            for (int i = 0; i < n; i++)
            {
                int length = si[2 * i];
                char* string = strings[si[2 * i + 1]];
                char* predicate;
                if (length == max)
                    predicate = predicate_max;
                else if (length == min)
                    predicate = predicate_min;
                else
                    predicate = predicate_ave;
                printf("\"%s\" %s %d %s\n",
                    string, has_length, length, predicate);
            }

            free(si);
        }
        else
        {
            fputs("unable allocate memory buffer", stderr);
        }
    }
}

int main(int argc, char* argv[])
{
    char* list[] = { "abcd", "123456789", "abcdef", "1234567" };

    compareAndReportStringsLength(list, 4);

    return EXIT_SUCCESS;
}







Python: A = 'I am string'
B = 'I am string too'

if len(A) > len(B):
    print('"' + A + '"', 'has length', len(A), 'and is the longest of the two strings')
    print('"' + B + '"', 'has length', len(B), 'and is the shortest of the two strings')
elif len(A) < len(B):
    print('"' + B + '"', 'has length', len(B), 'and is the longest of the two strings')
    print('"' + A + '"', 'has length', len(A), 'and is the shortest of the two strings')
else:
    print('"' + A + '"', 'has length', len(A), 'and it is as long as the second string')
    print('"' + B + '"', 'has length', len(B), 'and it is as long as the second string')
Task: Sorting algorithms_Shell sort

C: #include <stdio.h>

void shell_sort (int *a, int n) {
    int h, i, j, t;
    for (h = n; h /= 2;) {
        for (i = h; i < n; i++) {
            t = a[i];
            for (j = i; j >= h && t < a[j - h]; j -= h) {
                a[j] = a[j - h];
            }
            a[j] = t;
        }
    }
}

int main (int ac, char **av) {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    shell_sort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}







Python: def shell(seq):
    inc = len(seq) // 2
    while inc:
        for i, el in enumerate(seq[inc:], inc):
            while i >= inc and seq[i - inc] > el:
                seq[i] = seq[i - inc]
                i -= inc
            seq[i] = el
        inc = 1 if inc == 2 else inc * 5 // 11
Task: Doubly-linked list_Definition

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

struct List {
   struct MNode *head;
   struct MNode *tail;
   struct MNode *tail_pred;
};

struct MNode {
   struct MNode *succ;
   struct MNode *pred;
};

typedef struct MNode *NODE;
typedef struct List *LIST;


LIST newList(void);


int isEmpty(LIST);


NODE getTail(LIST);


NODE getHead(LIST);


NODE addTail(LIST, NODE);


NODE addHead(LIST, NODE);


NODE remHead(LIST);


NODE remTail(LIST);


NODE insertAfter(LIST, NODE, NODE);


NODE removeNode(LIST, NODE);


LIST newList(void)
{
    LIST tl = malloc(sizeof(struct List));
    if ( tl != NULL )
    {
       tl->tail_pred = (NODE)&tl->head;
       tl->tail = NULL;
       tl->head = (NODE)&tl->tail;
       return tl;
    }
    return NULL;
}

int isEmpty(LIST l)
{
   return (l->head->succ == 0);
}

NODE getHead(LIST l)
{
  return l->head;
}

NODE getTail(LIST l)
{
  return l->tail_pred;
}


NODE addTail(LIST l, NODE n)
{
    n->succ = (NODE)&l->tail;
    n->pred = l->tail_pred;
    l->tail_pred->succ = n;
    l->tail_pred = n;
    return n;
}

NODE addHead(LIST l, NODE n)
{
    n->succ = l->head;
    n->pred = (NODE)&l->head;
    l->head->pred = n;
    l->head = n;
    return n;
}

NODE remHead(LIST l)
{
   NODE h;
   h = l->head;
   l->head = l->head->succ;
   l->head->pred = (NODE)&l->head;
   return h;
}

NODE remTail(LIST l)
{
   NODE t;
   t = l->tail_pred;
   l->tail_pred = l->tail_pred->pred;
   l->tail_pred->succ = (NODE)&l->tail;
   return t;
}

NODE insertAfter(LIST l, NODE r, NODE n)
{
   n->pred = r; n->succ = r->succ;
   n->succ->pred = n; r->succ = n;
   return n;
}

NODE removeNode(LIST l, NODE n)
{
   n->pred->succ = n->succ;
   n->succ->pred = n->pred;
   return n;
}







Python: from collections import deque

some_list = deque(["a", "b", "c"])
print(some_list)

some_list.appendleft("Z")
print(some_list)

for value in reversed(some_list):
    print(value)
Task: Letter frequency

C: 
int frequency[26];
int ch;
FILE* txt_file = fopen ("a_text_file.txt", "rt");


for (ch = 0; ch < 26; ch++)
    frequency[ch] = 0;

while (1) {
    ch = fgetc(txt_file);
    if (ch == EOF) break; 

    
    if ('a' <= ch && ch <= 'z')      
        frequency[ch-'a']++;
    else if ('A' <= ch && ch <= 'Z') 
        frequency[ch-'A']++;
}







Python: import collections, sys

def filecharcount(openfile):
    return sorted(collections.Counter(c for l in openfile for c in l).items())

f = open(sys.argv[1])
print(filecharcount(f))
Task: Permutation test

C: #include <stdio.h>

int data[] = {  85, 88, 75, 66, 25, 29, 83, 39, 97,
                68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };

int pick(int at, int remain, int accu, int treat)
{
        if (!remain) return (accu > treat) ? 1 : 0;

        return  pick(at - 1, remain - 1, accu + data[at - 1], treat) +
                ( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}

int main()
{
        int treat = 0, i;
        int le, gt;
        double total = 1;
        for (i = 0; i < 9; i++) treat += data[i];
        for (i = 19; i > 10; i--) total *= i;
        for (i = 9; i > 0; i--) total /= i;

        gt = pick(19, 9, 0, treat);
        le = total - gt;

        printf("<= : %f%%  %d\n > : %f%%  %d\n",
               100 * le / total, le, 100 * gt / total, gt);
        return 0;
}







Python: from itertools import combinations as comb

def statistic(ab, a):
    sumab, suma = sum(ab), sum(a)
    return ( suma / len(a) -
             (sumab -suma) / (len(ab) - len(a)) )

def permutationTest(a, b):
    ab = a + b
    Tobs = statistic(ab, a)
    under = 0
    for count, perm in enumerate(comb(ab, len(a)), 1):
        if statistic(ab, perm) <= Tobs:
            under += 1
    return under * 100. / count

treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
controlGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
under = permutationTest(treatmentGroup, controlGroup)
print("under=%.2f%%, over=%.2f%%" % (under, 100. - under))
Task: Möbius function

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

int main() {
    const int MU_MAX = 1000000;
    int i, j;
    int *mu;
    int sqroot;

    sqroot = (int)sqrt(MU_MAX);

    mu = malloc((MU_MAX + 1) * sizeof(int));

    for (i = 0; i < MU_MAX;i++) {
        mu[i] = 1;
    }

    for (i = 2; i <= sqroot; i++) {
        if (mu[i] == 1) {
            
            for (j = i; j <= MU_MAX; j += i) {
                mu[j] *= -i;
            }
            
            for (j = i * i; j <= MU_MAX; j += i * i) {
                mu[j] = 0;
            }
        }
    }

    for (i = 2; i <= MU_MAX; i++) {
        if (mu[i] == i) {
            mu[i] = 1;
        } else if (mu[i] == -i) {
            mu[i] = -1;
        } else if (mu[i] < 0) {
            mu[i] = 1;
        } else if (mu[i] > 0) {
            mu[i] = -1;
        }
    }

    printf("First 199 terms of the möbius function are as follows:\n    ");
    for (i = 1; i < 200; i++) {
        printf("%2d  ", mu[i]);
        if ((i + 1) % 20 == 0) {
            printf("\n");
        }
    }

    free(mu);
    return 0;
}







Python: 













 


def isPrime(n) :
 
    if (n < 2) :
        return False
    for i in range(2, n + 1) :
        if (i * i <= n and n % i == 0) :
            return False
    return True
 
def mobius(N) :
     
    
    if (N == 1) :
        return 1
 
    
    
    
    p = 0
    for i in range(1, N + 1) :
        if (N % i == 0 and
                isPrime(i)) :
 
            
            
            if (N % (i * i) == 0) :
                return 0
            else :
 
                
                
                p = p + 1
 
    
    
    
    
    if(p % 2 != 0) :
        return -1
    else :
        return 1
 

print("Mobius numbers from 1..99:")
      
for i in range(1, 100):
  print(f"{mobius(i):>4}", end = '')

  if i % 20 == 0: print()
Task: Increment a numerical string

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


char * incr(char *s)
{
	int i, begin, tail, len;
	int neg = (*s == '-');
	char tgt = neg ? '0' : '9';

	
	if (!strcmp(s, "-1")) {
		s[0] = '0', s[1] = '\0';
		return s;
	}

	len = strlen(s);
	begin = (*s == '-' || *s == '+') ? 1 : 0;

	
	for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);

	if (tail < begin && !neg) {
		
		if (!begin) s = realloc(s, len + 2);
		s[0] = '1';
		for (i = 1; i <= len - begin; i++) s[i] = '0';
		s[len + 1] = '\0';
	} else if (tail == begin && neg && s[1] == '1') {
		
		for (i = 1; i < len - begin; i++) s[i] = '9';
		s[len - 1] = '\0';
	} else { 
		for (i = len - 1; i > tail; i--)
			s[i] = neg ? '9' : '0';
		s[tail] += neg ? -1 : 1;
	}

	return s;
}

void string_test(const char *s)
{
	char *ret = malloc(strlen(s));
	strcpy(ret, s);

	printf("text: %s\n", ret);
	printf("  ->: %s\n", ret = incr(ret));
	free(ret);
}

int main()
{
	string_test("+0");
	string_test("-1");
	string_test("-41");
	string_test("+41");
	string_test("999");
	string_test("+999");
	string_test("109999999999999999999999999999999999999999");
	string_test("-100000000000000000000000000000000000000000000");

	return 0;
}







Python: next = str(int('123') + 1)
Task: Strip a set of characters from a string

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

  
char *strip_chars(const char *string, const char *chars)
{
  char * newstr = malloc(strlen(string) + 1);
  int counter = 0;

  for ( ; *string; string++) {
    if (!strchr(chars, *string)) {
      newstr[ counter ] = *string;
      ++ counter;
    }
  }

  newstr[counter] = 0;
  return newstr;
}

int main(void)
{
  char *new = strip_chars("She was a soul stripper. She took my heart!", "aei");
  printf("%s\n", new);

  free(new);
  return 0;
}







Python: >>> def stripchars(s, chars):
...     return s.translate(None, chars)
... 
>>> stripchars("She was a soul stripper. She took my heart!", "aei")
'Sh ws  soul strppr. Sh took my hrt!'
Task: Sorting algorithms_Permutation sort

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

typedef int(*cmp_func)(const void*, const void*);

void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
	char *p, *q, *tmp = malloc(msize);
#	define A(i) ((char *)a + msize * (i))
#	define swap(a, b) {\
		memcpy(tmp, a, msize);\
		memcpy(a, b, msize);\
		memcpy(b, tmp, msize);	}
	while (1) {
		
		for (p = A(n - 1); (void*)p > a; p = q)
			if (_cmp(q = p - msize, p) > 0)
				break;

		if ((void*)p <= a) break;

		
		for (p = A(n - 1); p > q; p-= msize)
			if (_cmp(q, p) > 0) break;

		swap(p, q); 
		
		for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)
			swap(p, q);
	}
	free(tmp);
}

int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }

int main()
{
	int i;
	const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" };
	perm_sort(strs, 5, sizeof(*strs), scmp);

	for (i = 0; i < 5; i++)
		printf("%s\n", strs[i]);
	return 0;
}







Python: from itertools import permutations

in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
Task: Averages_Arithmetic mean

C: #include <stdio.h>

double mean(double *v, int len)
{
	double sum = 0;
	int i;
	for (i = 0; i < len; i++)
		sum += v[i];
	return sum / len;
}

int main(void)
{
	double v[] = {1, 2, 2.718, 3, 3.142};
	int i, len;
	for (len = 5; len >= 0; len--) {
		printf("mean[");
		for (i = 0; i < len; i++)
			printf(i ? ", %g" : "%g", v[i]);
		printf("] = %g\n", mean(v, len));
	}

	return 0;
}







Python: from math import fsum
def average(x):
    return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Task: Entropy

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
 
#define MAXLEN 100 
 
int makehist(unsigned char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}
 
double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}
 
int main(void){
	unsigned char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	scanf("%[^\n]",S);
	len=strlen(S);
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);
	
	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}







Python: from __future__ import division
import math

def hist(source):
    hist = {}; l = 0;
    for e in source:
        l += 1
        if e not in hist:
            hist[e] = 0
        hist[e] += 1
    return (l,hist)

def entropy(hist,l):
    elist = []
    for v in hist.values():
        c = v / l
        elist.append(-c * math.log(c ,2))
    return sum(elist)

def printHist(h):
    flip = lambda (k,v) : (v,k)
    h = sorted(h.iteritems(), key = flip)
    print 'Sym\thi\tfi\tInf'
    for (k,v) in h:
        print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2))
    
    

source = "1223334444"
(l,h) = hist(source);
print '.[Results].'
print 'Length',l
print 'Entropy:', entropy(h, l)
printHist(h)
Task: Tokenize a string with escaping

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

#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'

typedef char* Str; 


unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );



int main() {
    char s[] = STR_DEMO;
    unsigned int i, q;

    Str *list = Tokenize( s, SEP, ESC, &q );

    if( list != NULL ) {
        printf( "\n Original string: %s\n\n", STR_DEMO );
        printf( " %d tokens:\n\n", q );

        for( i=0; i<q; ++i )
            printf( " %4d. %s\n", i+1, list[i] );

        free( list );
    }

    return 0;
}



unsigned int ElQ( const char *s, char sep, char esc ) {
    unsigned int q, e;
    const char *p;

    for( e=0, q=1, p=s; *p; ++p ) {
        if( *p == esc )
            e = !e;
        else if( *p == sep )
            q += !e;
        else e = 0;
    }

    return q;
}



Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
    Str *list = NULL;

    *q = ElQ( s, sep, esc );
    list = malloc( *q * sizeof(Str) );

    if( list != NULL ) {
        unsigned int e, i;
        char *p;

        i = 0;
        list[i++] = s;

        for( e=0, p=s; *p; ++p ) {
            if( *p == esc ) {
                e = !e;
            }
            else if( *p == sep && !e ) {
                list[i++] = p+1;
                *p = '\0';
            }
            else {
                e = 0;
            }
        }
    }

    return list;
}







Python: def token_with_escape(a, escape = '^', separator = '|'):
    
    result = []
    token = ''
    state = 0
    for c in a:
        if state == 0:
            if c == escape:
                state = 1
            elif c == separator:
                result.append(token)
                token = ''
            else:
                token += c
        elif state == 1:
            token += c
            state = 0
    result.append(token)
    return result
Task: Forward difference

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

double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
	unsigned int i, j;
	double* y;

	
	if (order >= len) return 0;

	y = malloc(sizeof(double) * len);
	if (!order) {
		memcpy(y, x, sizeof(double) * len);
		return y;
	}

	
	for (j = 0; j < order; j++, x = y)
		for (i = 0, len--; i < len; i++)
			y[i] = x[i + 1] - x[i];

	y = realloc(y, sizeof(double) * len);
	return y;
}

int main(void)
{
	double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
	int i, len = sizeof(x) / sizeof(x[0]);

	y = fwd_diff(x, len, 1);
	for (i = 0; i < len - 1; i++)
		printf("%g ", y[i]);
	putchar('\n');

	return 0;
}







Python: >>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
>>> 
>>> difn = lambda s, n: difn(dif(s), n-1) if n else s

>>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 0)
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
>>> difn(s, 1)
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
>>> difn(s, 2)
[54, -40, 22, 17, 13, -73, 100, -32]

>>> from pprint import pprint
>>> pprint( [difn(s, i) for i in xrange(10)] )
[[90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
 [-43, 11, -29, -7, 10, 23, -50, 50, 18],
 [54, -40, 22, 17, 13, -73, 100, -32],
 [-94, 62, -5, -4, -86, 173, -132],
 [156, -67, 1, -82, 259, -305],
 [-223, 68, -83, 341, -564],
 [291, -151, 424, -905],
 [-442, 575, -1329],
 [1017, -1904],
 [-2921]]
Task: Primality by trial division

C: int is_prime(unsigned int n)
{
	unsigned int p;
	if (!(n & 1) || n < 2 ) return n == 2;

	
	for (p = 3; p <= n/p; p += 2)
		if (!(n % p)) return 0;
	return 1;
}







Python: def prime(a):
    return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Task: Evaluate binomial coefficients

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



static unsigned long gcd_ui(unsigned long x, unsigned long y) {
  unsigned long t;
  if (y < x) { t = x; x = y; y = t; }
  while (y > 0) {
    t = y;  y = x % y;  x = t;  
  }
  return x;
}

unsigned long binomial(unsigned long n, unsigned long k) {
  unsigned long d, g, r = 1;
  if (k == 0) return 1;
  if (k == 1) return n;
  if (k >= n) return (k == n);
  if (k > n/2) k = n-k;
  for (d = 1; d <= k; d++) {
    if (r >= ULONG_MAX/n) {  
      unsigned long nr, dr;  
      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;
      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;
      if (r >= ULONG_MAX/nr) return 0;  
      r *= nr;
      r /= dr;
      n--;
    } else {
      r *= n--;
      r /= d;
    }
  }
  return r;
}

int main() {
    printf("%lu\n", binomial(5, 3));
    printf("%lu\n", binomial(40, 19));
    printf("%lu\n", binomial(67, 31));
    return 0;
}







Python: def binomialCoeff(n, k):
    result = 1
    for i in range(1, k+1):
        result = result * (n-i+1) / i
    return result

if __name__ == "__main__":
    print(binomialCoeff(5, 3))
Task: Collections

C: #define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) 
int ar[10];               
ar[0] = 1;                
ar[1] = 2;

int* p;                   
for (p=ar;                
       p<(ar+cSize(ar));  
       p++) {             
  printf("%d\n",*p);      
}                         







Python: collection = [0, '1']                 
x = collection[0]                     
collection.append(2)                  
collection.insert(0, '-1')            
y = collection[0]                     
collection.extend([2,'3'])            
collection += [2,'3']                 
collection[2:6]                       
len(collection)                       
collection = (0, 1)                   
collection[:]                         
collection[-4:-1]                     
collection[::2]                       
collection="some string"              
x = collection[::-1]                  
collection[::2] == "some string"[::2] 
collection.__getitem__(slice(0,len(collection),2))  
collection = {0: "zero", 1: "one"}    
collection['zero'] = 2                
collection = set([0, '1'])
Task: Singly-linked list_Traversal

C: struct link *first;

struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
  
}







Python: for node in lst:
    print node.value
Task: Bitmap_Write a PPM file

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

int main(void)
{
  const int dimx = 800, dimy = 800;
  int i, j;
  FILE *fp = fopen("first.ppm", "wb"); 
  (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
  for (j = 0; j < dimy; ++j)
  {
    for (i = 0; i < dimx; ++i)
    {
      static unsigned char color[3];
      color[0] = i % 256;  
      color[1] = j % 256;  
      color[2] = (i * j) % 256;  
      (void) fwrite(color, 1, 3, fp);
    }
  }
  (void) fclose(fp);
  return EXIT_SUCCESS;
}







Python: 
import io
ppmfileout = io.StringIO('')

def writeppmp3(self, f):
    self.writeppm(f, ppmformat='P3')
        
def writeppm(self, f, ppmformat='P6'):
    assert ppmformat in ['P3', 'P6'], 'Format wrong'
    magic = ppmformat + '\n'
    comment = '
    maxval = max(max(max(bit) for bit in row) for row in self.map)
    assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte'
    if ppmformat == 'P6':
        fwrite = lambda s: f.write(bytes(s, 'UTF-8'))
        maxval = 255
    else:
        fwrite = f.write
        numsize=len(str(maxval))
    fwrite(magic)
    fwrite(comment)
    fwrite('%i %i\n%i\n' % (self.width, self.height, maxval))
    for h in range(self.height-1, -1, -1):
        for w in range(self.width):
            r, g, b = self.get(w, h)
            if ppmformat == 'P3':
                fwrite('   %*i %*i %*i' % (numsize, r, numsize, g, numsize, b))
            else:
                fwrite('%c%c%c' % (r, g, b))
        if ppmformat == 'P3':
            fwrite('\n')

Bitmap.writeppmp3 = writeppmp3
Bitmap.writeppm = writeppm


bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))

bitmap.writeppmp3(ppmfileout)

print(ppmfileout.getvalue())




ppmfileout = open('tmp.ppm', 'wb')
bitmap.writeppm(ppmfileout)
ppmfileout.close()
Task: Delete a file

C: #include <stdio.h>

int main() {
  remove("input.txt");
  remove("/input.txt");
  remove("docs");
  remove("/docs");
  return 0;
}







Python: import os

os.remove("output.txt")
os.rmdir("docs")

os.remove("/output.txt")
os.rmdir("/docs")