WeixiangYan/CodeTransOcean huggingface dataset:
Task: Euler method


C++: #include <iomanip>
#include <iostream>

typedef double F(double,double);


void euler(F f, double y0, double a, double b, double h)
{
    double y = y0;
    for (double t = a; t < b; t += h)
    {
        std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
        y += h * f(t, y);
    }
    std::cout << "done\n";
}


double newtonCoolingLaw(double, double t)
{
    return -0.07 * (t - 20);
}

int main()
{
    euler(newtonCoolingLaw, 100, 0, 100,  2);
    euler(newtonCoolingLaw, 100, 0, 100,  5);
    euler(newtonCoolingLaw, 100, 0, 100, 10);
}






Python: def euler(f,y0,a,b,h):
	t,y = a,y0
	while t <= b:
		print "%6.3f %6.3f" % (t,y)
		t += h
		y += h * f(t,y)

def newtoncooling(time, temp):
	return -0.07 * (temp - 20)

euler(newtoncooling,100,0,100,10)
Task: Sequence of non-squares


C++: #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>

double nextNumber( double number ) {
   return number + floor( 0.5 + sqrt( number ) ) ;
}

int main( ) {
   std::vector<double> non_squares ;
   typedef std::vector<double>::iterator SVI ;
   non_squares.reserve( 1000000 ) ;   
   
   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
      non_squares.push_back( nextNumber( i ) ) ;  
   
   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
	 std::ostream_iterator<double>(std::cout, " " ) ) ;     
   std::cout << '\n' ;
   
   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
	 boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
   if ( found != non_squares.end( ) ) {
      std::cout << "Found a square number in the sequence!\n" ;
      std::cout << "It is " << *found << " !\n" ;
   }
   else {
      std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
   }
   return 0 ;
}






Python: >>> from math import floor, sqrt
>>> def non_square(n):
        return n + floor(1/2 + sqrt(n))

>>> 
>>> print(*map(non_square, range(1, 23)))
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

>>> 
>>> def is_square(n):
        return sqrt(n).is_integer()

>>> non_squares = map(non_square, range(1, 10 ** 6))
>>> next(filter(is_square, non_squares))
StopIteration                             Traceback (most recent call last)
<ipython-input-45-f32645fc1c0a> in <module>()
      1 non_squares = map(non_square, range(1, 10 ** 6))
----> 2 next(filter(is_square, non_squares))

StopIteration:
Task: Substring


C++: #include <iostream>
#include <string>

int main()
{
  std::string s = "0123456789";

  int const n = 3;
  int const m = 4;
  char const c = '2';
  std::string const sub = "456";

  std::cout << s.substr(n, m)<< "\n";
  std::cout << s.substr(n) << "\n";
  std::cout << s.substr(0, s.size()-1) << "\n";
  std::cout << s.substr(s.find(c), m) << "\n";
  std::cout << s.substr(s.find(sub), m) << "\n";
}






Python: >>> s = 'abcdefgh'
>>> n, m, char, chars = 2, 3, 'd', 'cd'
>>> 
>>> s[n-1:n+m-1]
'bcd'
>>> 
>>> s[n-1:]
'bcdefgh'
>>> 
>>> s[:-1]
'abcdefg'
>>> 
>>> indx = s.index(char)
>>> s[indx:indx+m]
'def'
>>> 
>>> indx = s.index(chars)
>>> s[indx:indx+m]
'cde'
>>>
Task: JortSort


C++: #include <algorithm>
#include <string>
#include <iostream>
#include <iterator> 

class jortSort {
public:
    template<class T>
    bool jort_sort( T* o, size_t s ) {
        T* n = copy_array( o, s );
        sort_array( n, s );
        bool r = false;

        if( n ) {
            r = check( o, n, s );
            delete [] n;
        }
        return r;
    }

private:
    template<class T>
    T* copy_array( T* o, size_t s ) {
        T* z = new T[s];
        memcpy( z, o, s * sizeof( T ) );
        
        return z;
    }
    template<class T>
    void sort_array( T* n, size_t s ) {
        std::sort( n, n + s );
    }
    template<class T>
    bool check( T* n, T* o, size_t s ) {
        for( size_t x = 0; x < s; x++ )
            if( n[x] != o[x] ) return false;
        return true;
    }
};

jortSort js;

template<class T>
void displayTest( T* o, size_t s ) {
    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
    std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}

int main( int argc, char* argv[] ) {
    const size_t s = 5;
    std::string oStr[] = { "5", "A", "D", "R", "S" };
    displayTest( oStr, s );
    std::swap( oStr[0], oStr[1] );
    displayTest( oStr, s );

    int oInt[] = { 1, 2, 3, 4, 5 };
    displayTest( oInt, s );
    std::swap( oInt[0], oInt[1] );
    displayTest( oInt, s );

    return 0;
}






Python: >>> def jortsort(sequence):
	return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
	print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>>
Task: Leap year


C++: #include <iostream>

bool is_leap_year(int year) {
  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

int main() {
  for (auto year : {1900, 1994, 1996, 1997, 2000}) {
    std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
  }
}






Python: import calendar
calendar.isleap(year)
Task: Combinations and permutations


C++: #include <boost/multiprecision/gmp.hpp>
#include <iostream>

using namespace boost::multiprecision;

mpz_int p(uint n, uint p) {
    mpz_int r = 1;
    mpz_int k = n - p;
    while (n > k)
        r *= n--;
    return r;
}

mpz_int c(uint n, uint k) {
    mpz_int r = p(n, k);
    while (k)
        r /= k--;
    return r;
}

int main() {
    for (uint i = 1u; i < 12u; i++)
        std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
    for (uint i = 10u; i < 60u; i += 10u)
        std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;

    return 0;
}






Python: from __future__ import print_function

from scipy.misc import factorial as fact
from scipy.misc import comb

def perm(N, k, exact=0):
    return comb(N, k, exact) * fact(k, exact)

exact=True
print('Sample Perms 1..12')
for N in range(1, 13):
    k = max(N-2, 1)
    print('%iP%i =' % (N, k), perm(N, k, exact), end=', ' if N % 5 else '\n')
          
print('\n\nSample Combs 10..60')
for N in range(10, 61, 10):
    k = N-2
    print('%iC%i =' % (N, k), comb(N, k, exact), end=', ' if N % 50 else '\n')

exact=False
print('\n\nSample Perms 5..1500 Using FP approximations')
for N in [5, 15, 150, 1500, 15000]:
    k = N-2
    print('%iP%i =' % (N, k), perm(N, k, exact))
          
print('\nSample Combs 100..1000 Using FP approximations')
for N in range(100, 1001, 100):
    k = N-2
    print('%iC%i =' % (N, k), comb(N, k, exact))
Task: Sort numbers lexicographically


C++: #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

void lexicographical_sort(std::vector<int>& numbers) {
    std::vector<std::string> strings(numbers.size());
    std::transform(numbers.begin(), numbers.end(), strings.begin(),
                   [](int i) { return std::to_string(i); });
    std::sort(strings.begin(), strings.end());
    std::transform(strings.begin(), strings.end(), numbers.begin(),
                   [](const std::string& s) { return std::stoi(s); });
}

std::vector<int> lexicographically_sorted_vector(int n) {
    std::vector<int> numbers(n >= 1 ? n : 2 - n);
    std::iota(numbers.begin(), numbers.end(), std::min(1, n));
    lexicographical_sort(numbers);
    return numbers;
}

template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
    out << '[';
    if (!v.empty()) {
        auto i = v.begin();
        out << *i++;
        for (; i != v.end(); ++i)
            out << ',' << *i;
    }
    out << "]\n";
}

int main(int argc, char** argv) {
    for (int i : { 0, 5, 13, 21, -22 }) {
        std::cout << i << ": ";
        print_vector(std::cout, lexicographically_sorted_vector(i));
    }
    return 0;
}






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


C++: #include <iostream>
#include <algorithm>
#include <string>
#include <list>

using namespace std;

bool cmp(const string& a, const string& b)
{
    return b.length() < a.length(); 
}

void compareAndReportStringsLength(list<string> listOfStrings)
{
    if (!listOfStrings.empty())
    {
        char Q = '"';
        string has_length(" has length ");
        string predicate_max(" and is the longest string");
        string predicate_min(" and is the shortest string");
        string predicate_ave(" and is neither the longest nor the shortest string");

        list<string> ls(listOfStrings); 
        ls.sort(cmp);
        int max = ls.front().length();
        int min = ls.back().length();

        for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
        {
            int length = s->length();
            string* predicate;
            if (length == max)
                predicate = &predicate_max;
            else if (length == min)
                predicate = &predicate_min;
            else
                predicate = &predicate_ave;

            cout << Q << *s << Q << has_length << length << *predicate << endl;
        }
    }
}

int main(int argc, char* argv[])
{
    list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
    compareAndReportStringsLength(listOfStrings);

    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 <time.h>
#include <iostream>


using namespace std;


const int MAX = 126;
class shell
{
public:
    shell() 
    { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }

    void sort( int* a, int count )
    {
	_cnt = count;
	for( int x = 0; x < 9; x++ )
	    if( count > _gap[x] )
	    { _idx = x; break; }

	sortIt( a );
    }

private:	
    void sortIt( int* arr )
    {
	bool sorted = false;
	while( true )
	{
	    sorted = true;
	    int st = 0;
	    for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
	    {
		if( arr[st] > arr[x] )
		{ swap( arr[st], arr[x] ); sorted = false; }
		st = x;
	    }
	    if( ++_idx >= 8 ) _idx = 8;
	    if( sorted && _idx == 8 ) break;
	}
    }

    void swap( int& a, int& b ) { int t = a; a = b; b = t; }

    int _gap[9], _idx, _cnt;
};

int main( int argc, char* argv[] )
{
    srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
    for( int x = 0; x < MAX; x++ )
	arr[x] = rand() % MAX - rand() % MAX;

    cout << " Before: \n=========\n";
    for( int x = 0; x < 7; x++ )
    {
	for( int a = 0; a < 18; a++ )
	{ cout << arr[x * 18 + a] << " "; }
	cout << endl;
    }
    cout << endl; shell s; s.sort( arr, MAX );
	
    cout << " After: \n========\n";
    for( int x = 0; x < 7; x++ )
    {
	for( int a = 0; a < 18; a++ )
	{ cout << arr[x * 18 + a] << " "; }
	cout << endl;
    }
    cout << endl << endl; return system( "pause" );
}







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 <iostream>
#include <list>

int main ()
{
    std::list<int> numbers {1, 5, 7, 0, 3, 2};
    numbers.insert(numbers.begin(), 9); 
    numbers.insert(numbers.end(), 4); 
    auto it = std::next(numbers.begin(), numbers.size() / 2); 
    numbers.insert(it, 6); 
    for(const auto& i: numbers)
        std::cout << i << ' ';
    std::cout << '\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++: #include <fstream>
#include <iostream>

int main()
{
	std::ifstream input("filename.txt", std::ios_base::binary);
	if (!input)
	{
		std::cerr << "error: can't open file\n";
		return -1;
	}

	size_t count[256];
	std::fill_n(count, 256, 0);

	for (char c; input.get(c); ++count[uint8_t(c)]) 
		; 

	for (size_t i = 0; i < 256; ++i)
	{
		if (count[i] && isgraph(i)) 
		{
			std::cout << char(i) << " = " << count[i] << '\n';
		}
	}
}






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<iostream>
#include<vector>
#include<numeric>
#include<functional>

class
{
public:
    int64_t operator()(int n, int k){ return partial_factorial(n, k) / factorial(n - k);}
private:
    int64_t partial_factorial(int from, int to) { return from == to ? 1 : from * partial_factorial(from - 1, to); }
    int64_t factorial(int n) { return n == 0 ? 1 : n * factorial(n - 1);}
}combinations;

int main()
{
    static constexpr int treatment = 9;
    const std::vector<int> data{ 85, 88, 75, 66, 25, 29, 83, 39, 97,
                                 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };

    int treated = std::accumulate(data.begin(), data.begin() + treatment, 0);

    std::function<int (int, int, int)> pick;
    pick = [&](int n, int from, int accumulated)
            {
                if(n == 0)
                    return accumulated > treated ? 1 : 0;
                else
                    return pick(n - 1, from - 1, accumulated + data[from - 1]) +
                            (from > n ? pick(n, from - 1, accumulated) : 0);
            };

    int total   = combinations(data.size(), treatment);
    int greater = pick(treatment, data.size(), 0);
    int lesser  = total - greater;

    std::cout << "<= : " << 100.0 * lesser  / total << "%  " << lesser  << std::endl
              << " > : " << 100.0 * greater / total << "%  " << greater << std::endl;
}






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 <iomanip>
#include <iostream>
#include <vector>

constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;

int mobiusFunction(int n) {
    if (!MU.empty()) {
        return MU[n];
    }

    
    MU.resize(MU_MAX + 1, 1);
    int root = sqrt(MU_MAX);

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

    for (int 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;
        }
    }

    return MU[n];
}

int main() {
    std::cout << "First 199 terms of the möbius function are as follows:\n    ";
    for (int n = 1; n < 200; n++) {
        std::cout << std::setw(2) << mobiusFunction(n) << "  ";
        if ((n + 1) % 20 == 0) {
            std::cout << '\n';
        }
    }

    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 <cstdlib>
#include <string>
#include <sstream>


std::string s = "12345";

int i;
std::istringstream(s) >> i;
i++;



std::ostringstream oss;
if (oss << i) s = oss.str();






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


C++: #include <algorithm>
#include <iostream>
#include <string>

std::string stripchars(std::string str, const std::string &chars)
{
    str.erase(
        std::remove_if(str.begin(), str.end(), [&](char c){
            return chars.find(c) != std::string::npos;
        }),
        str.end()
    );
    return str;
}

int main()
{
    std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
    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 <algorithm>

template<typename ForwardIterator>
 void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
  while (std::next_permutation(begin, end))
  {
    
  }
}






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 <vector>

double mean(const std::vector<double>& numbers)
{
     if (numbers.size() == 0)
          return 0;

     double sum = 0;
     for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
          sum += *i;
     return sum / numbers.size();
}






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 <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>

double log2( double number ) {
   return log( number ) / log( 2 ) ;
}

int main( int argc , char *argv[ ] ) {
   std::string teststring( argv[ 1 ] ) ;
   std::map<char , int> frequencies ;
   for ( char c : teststring )
     frequencies[ c ] ++ ;
   int numlen = teststring.length( ) ;
   double infocontent = 0 ;
   for ( std::pair<char , int> p : frequencies ) {
      double freq = static_cast<double>( p.second ) / numlen ;
      infocontent -= freq * log2( freq ) ;
   }
  
   std::cout << "The information content of " << teststring 
      << " is " << infocontent << std::endl ;
   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 <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

vector<string> tokenize(const string& input, char seperator, char escape) {
    vector<string> output;
    string token;

    bool inEsc = false;
    for (char ch : input) {
        if (inEsc) {
            inEsc = false;
        } else if (ch == escape) {
            inEsc = true;
            continue;
        } else if (ch == seperator) {
            output.push_back(token);
            token = "";
            continue;
        }
        token += ch;
    }
    if (inEsc)
        throw new invalid_argument("Invalid terminal escape");

    output.push_back(token);
    return output;
}

int main() {
    string sample = "one^|uno||three^^^^|four^^^|^cuatro|";

    cout << sample << endl;
    cout << '[';
    for (auto t : tokenize(sample, '|', '^')) {
        cout << '"' << t << "\", ";
    }
    cout << ']' << endl;

    return 0;
}






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: Hello world_Text


C++: #include <iostream>

int main () {
  std::cout << "Hello world!" << std::endl;
}






Python: print "Hello world!"