WeixiangYan/CodeTransOcean huggingface dataset:
Task: Date manipulation


C++: #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>


int main( ) {
   std::string datestring ("March 7 2009 7:30pm EST" ) ;
   
   
   
   std::vector<std::string> elements ;
   
   boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
   std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
      elements[ 2 ] ; 
   std::string timepart = elements[ 3 ] ;
   std::string timezone = elements[ 4 ] ;
   const char meridians[ ] = { 'a' , 'p' } ;
   
   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
   timepart = timepart.substr( 0 , found ) ; 
   elements.clear( ) ;
   boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
   if ( twelve_hour == "p" ) 
      hour += 12 ;
   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; 
   boost::local_time::tz_database tz_db ;
   tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
   
   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
   
   boost::gregorian::date_input_facet *f =
      new boost::gregorian::date_input_facet( "%B %d %Y"  ) ;
   std::stringstream ss ;
   ss << datepart ;
   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
   boost::gregorian::date d ;
   ss >> d ;
   boost::posix_time::time_duration td (  hour , minute , 0  ) ;
   
   
   boost::local_time::local_date_time lt ( d , td ,  dyc ,
	 boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
   std::cout << "local time: " << lt << '\n' ;
   ss.str( "" ) ;
   ss << lt ;
   
   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
   boost::local_time::local_date_time ltlater = lt + td2 ; 
   boost::gregorian::date_facet *f2 =
      new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
   std::cout << "12 hours after " << ss.str( )  << " it is " << ltlater << " !\n" ;
   
   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
   std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; 
   std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
   return 0 ;
}






Python: import datetime

def mt():
	datime1="March 7 2009 7:30pm EST"
	formatting = "%B %d %Y %I:%M%p "
	datime2 = datime1[:-3]  
	tdelta = datetime.timedelta(hours=12)		
	s3 = datetime.datetime.strptime(datime2, formatting)
	datime2 = s3+tdelta
	print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]

mt()
Task: Sorting algorithms_Sleep sort


C++: #include <chrono>
#include <iostream>
#include <thread>
#include <vector>

int main(int argc, char* argv[]) {
  std::vector<std::thread> threads;

  for (int i = 1; i < argc; ++i) {
    threads.emplace_back([i, &argv]() {
      int arg = std::stoi(argv[i]);
      std::this_thread::sleep_for(std::chrono::seconds(arg));
      std::cout << argv[i] << std::endl;
    });
  }

  for (auto& thread : threads) {
    thread.join();
  }
}






Python: from time import sleep
from threading import Timer

def sleepsort(values):
    sleepsort.result = []
    def add1(x):
        sleepsort.result.append(x)
    mx = values[0]
    for v in values:
        if mx < v: mx = v
        Timer(v, add1, [v]).start()
    sleep(mx+1)
    return sleepsort.result

if __name__ == '__main__':
    x = [3,2,4,7,3,6,9,1]
    if sleepsort(x) == sorted(x):
        print('sleep sort worked for:',x)
    else:
        print('sleep sort FAILED for:',x)
Task: Loops_Nested


C++: #include<cstdlib>
#include<ctime>
#include<iostream>

using namespace std;
int main()
{
    int arr[10][10];
    srand(time(NULL));
    for(auto& row: arr)
        for(auto& col: row)
            col = rand() % 20 + 1;

    ([&](){
       for(auto& row : arr)
           for(auto& col: row)
           {
               cout << col << endl;
               if(col == 20)return;
           }
    })();
    return 0;
}






Python: from random import randint

def do_scan(mat):
    for row in mat:
        for item in row:
            print item,
            if item == 20:
                print
                return
        print
    print

mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
Task: Pythagorean triples


C++: #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>

using namespace std;

auto CountTriplets(unsigned long long maxPerimeter)
{
    unsigned long long totalCount = 0;
    unsigned long long primitveCount = 0;
    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
    for(unsigned long long m = 2; m < max_M; ++m)
    {
        for(unsigned long long n = 1 + m % 2; n < m; n+=2)
        {
            if(gcd(m,n) != 1)
            {
                continue;
            }
            
            
            
            
            
            
            auto a = m * m - n * n;
            auto b = 2 * m * n;
            auto c = m * m + n * n;
            auto perimeter = a + b + c;
            if(perimeter <= maxPerimeter)
            {
                primitveCount++;
                totalCount+= maxPerimeter / perimeter;
            }
        }
    }
    
    return tuple(totalCount, primitveCount);
}


int main()
{
    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
        1000'000, 10'000'000, 100'000'000, 1000'000'000,
        10'000'000'000};  
    for(auto maxPerimeter : inputs)
    {
        auto [total, primitive] = CountTriplets(maxPerimeter);
        cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
    }
}






Python: from fractions import gcd


def pt1(maxperimeter=100):
    
    trips = []
    for a in range(1, maxperimeter):
        aa = a*a
        for b in range(a, maxperimeter-a+1):
            bb = b*b
            for c in range(b, maxperimeter-b-a+1):
                cc = c*c
                if a+b+c > maxperimeter or cc > aa + bb: break
                if aa + bb == cc:
                    trips.append((a,b,c, gcd(a, b) == 1))
    return trips

def pytrip(trip=(3,4,5),perim=100, prim=1):
    a0, b0, c0 = a, b, c = sorted(trip)
    t, firstprim = set(), prim>0
    while a + b + c <= perim:
        t.add((a, b, c, firstprim>0))
        a, b, c, firstprim = a+a0, b+b0, c+c0, False
    
    t2 = set()
    for a, b, c, firstprim in t:
        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
        if  a5 - b5 + c7 <= perim:
            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)
        if  a5 + b5 + c7 <= perim:
            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)
        if -a5 + b5 + c7 <= perim:
            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
    return t | t2

def pt2(maxperimeter=100):
    
    trips = pytrip((3,4,5), maxperimeter, 1)
    return trips

def printit(maxperimeter=100, pt=pt1):
    trips = pt(maxperimeter)
    print("  Up to a perimeter of %i there are %i triples, of which %i are primitive"
          % (maxperimeter,
             len(trips),
             len([prim for a,b,c,prim in trips if prim])))
  
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
    print(algo.__doc__)
    for maxperimeter in range(mn, mx+1, mn):
        printit(maxperimeter, algo)
Task: Remove duplicate elements


C++: #include <set>
#include <iostream>
using namespace std;

int main() {
    typedef set<int> TySet;
    int data[] = {1, 2, 3, 2, 3, 4};

    TySet unique_set(data, data + 6);

    cout << "Set items:" << endl;
    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)
          cout << *iter << " ";
    cout << endl;
}






Python: items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
Task: Look-and-say sequence


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

std::string lookandsay(const std::string& s)
{
    std::ostringstream r;

    for (std::size_t i = 0; i != s.length();) {
        auto new_i = s.find_first_not_of(s[i], i + 1);

        if (new_i == std::string::npos)
            new_i = s.length();

        r << new_i - i << s[i];
        i = new_i;
    }
    return r.str();
}

int main()
{
    std::string laf = "1";

    std::cout << laf << '\n';
    for (int i = 0; i < 10; ++i) {
        laf = lookandsay(laf);
        std::cout << laf << '\n';
    }
}






Python: def lookandsay(number):
    result = ""

    repeat = number[0]
    number = number[1:]+" "
    times = 1

    for actual in number:
        if actual != repeat:
            result += str(times)+repeat
            times = 1
            repeat = actual
        else:
            times += 1

    return result

num = "1"

for i in range(10):
    print num
    num = lookandsay(num)
Task: Totient function


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

class totient_calculator {
public:
    explicit totient_calculator(int max) : totient_(max + 1) {
        for (int i = 1; i <= max; ++i)
            totient_[i] = i;
        for (int i = 2; i <= max; ++i) {
            if (totient_[i] < i)
                continue;
            for (int j = i; j <= max; j += i)
                totient_[j] -= totient_[j] / i;
        }
    }
    int totient(int n) const {
        assert (n >= 1 && n < totient_.size());
        return totient_[n];
    }
    bool is_prime(int n) const {
        return totient(n) == n - 1;
    }
private:
    std::vector<int> totient_;
};

int count_primes(const totient_calculator& tc, int min, int max) {
    int count = 0;
    for (int i = min; i <= max; ++i) {
        if (tc.is_prime(i))
            ++count;
    }
    return count;
}

int main() {
    const int max = 10000000;
    totient_calculator tc(max);
    std::cout << " n  totient  prime?\n";
    for (int i = 1; i <= 25; ++i) {
        std::cout << std::setw(2) << i
            << std::setw(9) << tc.totient(i)
            << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n';
    }
    for (int n = 100; n <= max; n *= 10) {
        std::cout << "Count of primes up to " << n << ": "
            << count_primes(tc, 1, n) << '\n';
    }
    return 0;
}






Python: from math import gcd

def  φ(n):
    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)

if __name__ == '__main__':
    def is_prime(n):
        return φ(n) == n - 1
    
    for n in range(1, 26):
        print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n)  else ''}")
    count = 0
    for n in range(1, 10_000 + 1):
        count += is_prime(n)
        if n in {100, 1000, 10_000}:
            print(f"Primes up to {n}: {count}")
Task: Conditional structures


C++: template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;

template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
  typedef ThenType type;
};

template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
  typedef ElseType type;
};


ifthenelse<INT_MAX == 32767, 
           long int,         
           int>              
  ::type myvar;              






Python: if x == 0:
    foo()
elif x == 1:
    bar()
elif x == 2:
    baz()
else:
    qux()

match x:
    0 => foo()
    1 => bar()
    2 => baz()
    _ => qux()

(a) ? b : c
Task: Fractran


C++: #include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
#include <cmath>

using namespace std;

class fractran
{
public:
    void run( std::string p, int s, int l  )
    {
        start = s; limit = l;
        istringstream iss( p ); vector<string> tmp;
        copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) );

        string item; vector< pair<float, float> > v;
	pair<float, float> a;
	for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ )
	{
	    string::size_type pos = ( *i ).find( '/', 0 );
	    if( pos != std::string::npos )
	    {
		a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) );
		v.push_back( a );
	    }
	}
		
	exec( &v );
    }

private:
    void exec( vector< pair<float, float> >* v )
    {
	int cnt = 0;
	while( cnt < limit )
	{
	    cout << cnt << " : " << start << "\n";
	    cnt++;
	    vector< pair<float, float> >::iterator it = v->begin();
	    bool found = false; float r;
	    while( it != v->end() )
	    {
		r  = start * ( ( *it ).first / ( *it ).second );
		if( r == floor( r ) )
		{
		    found = true;
		    break;
		}
		++it;
	    }

	    if( found ) start = ( int )r;
	    else break;
	}
    }
    int start, limit;
};
int main( int argc, char* argv[] )
{
    fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 );
    cin.get();
    return 0;
}






Python: from fractions import Fraction

def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
                        '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
                        '13 / 11, 15 / 14, 15 / 2, 55 / 1'):
    flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]

    n = Fraction(n)
    while True:
        yield n.numerator
        for f in flist:
            if (n * f).denominator == 1:
                break
        else:
            break
        n *= f
    
if __name__ == '__main__':
    n, m = 2, 15
    print('First %i members of fractran(%i):\n  ' % (m, n) +
          ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
Task: Sorting algorithms_Stooge sort


C++: #include <iostream>
#include <time.h>


using namespace std;


class stooge
{
public:
    void sort( int* arr, int start, int end )
    {
        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
	int n = end - start; if( n > 2 )
	{
	    n /= 3; sort( arr, start, end - n );
	    sort( arr, start + n, end ); sort( arr, start, end - n );
        }
    }
};

int main( int argc, char* argv[] )
{
    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; 
    cout << "before:\n";
    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << " "; }
    s.sort( a, 0, m ); cout << "\n\nafter:\n"; 
    for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; 
    return system( "pause" );
}






Python: >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
	if j is None:
		j = len(L) - 1
	if L[j] < L[i]:
		L[i], L[j] = L[j], L[i]
	if j - i > 1:
		t = (j - i + 1) // 3
		stoogesort(L, i  , j-t)
		stoogesort(L, i+t, j  )
		stoogesort(L, i  , j-t)
	return L

>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
Task: Sorting Algorithms_Circle Sort


C++: #include <iostream>

int circlesort(int* arr, int lo, int hi, int swaps) {
    if(lo == hi) {
        return swaps;
    }
    int high = hi;
    int low = lo;
    int mid = (high - low) / 2;
    while(lo < hi) {
        if(arr[lo] > arr[hi]) {
            int temp = arr[lo];
            arr[lo] = arr[hi];
            arr[hi] = temp;
            swaps++;
        }
        lo++;
        hi--;
    }

    if(lo == hi) {
        if(arr[lo] > arr[hi+1]) {
            int temp = arr[lo];
            arr[lo] = arr[hi+1];
            arr[hi+1] = temp;
            swaps++;
        }
    }
    swaps = circlesort(arr, low, low+mid, swaps);
    swaps = circlesort(arr, low+mid+1, high, swaps);
    return swaps;
}

void circlesortDriver(int* arr, int n) {
    do {
        for(int i = 0; i < n; i++) {
            std::cout << arr[i] << ' ';
        }
        std::cout << std::endl;
    } while(circlesort(arr, 0, n-1, 0));
}

int main() {
    int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };
    circlesortDriver(arr, sizeof(arr)/sizeof(int));
    return 0;
}






Python: 




def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
    
    n = R-L
    if n < 2:
        return 0
    swaps = 0
    m = n//2
    for i in range(m):
        if A[R-(i+1)] < A[L+i]:
            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
            swaps += 1
    if (n & 1) and (A[L+m] < A[L+m-1]):
        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
        swaps += 1
    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)

def circle_sort(L:list)->'sort A in place, returning the number of swaps':
    swaps = 0
    s = 1
    while s:
        s = circle_sort_backend(L, 0, len(L))
        swaps += s
    return swaps


if __name__ == '__main__':
    from random import shuffle
    for i in range(309):
        L = list(range(i))
        M = L[:]
        shuffle(L)
        N = L[:]
        circle_sort(L)
        if L != M:
            print(len(L))
            print(N)
            print(L)
Task: Sort using a custom comparator


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


struct icompare_char {
  bool operator()(char c1, char c2) {
    return std::toupper(c1) < std::toupper(c2);
  }
};


struct compare {
  bool operator()(std::string const& s1, std::string const& s2) {
    if (s1.length() > s2.length())
      return true;
    if (s1.length() < s2.length())
      return false;
    return std::lexicographical_compare(s1.begin(), s1.end(),
                                        s2.begin(), s2.end(),
                                        icompare_char());
  }
};

int main() {
  std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
  std::sort(strings, strings+8, compare());
  return 0;
}






Python: strings = "here are Some sample strings to be sorted".split()

def mykey(x):
    return -len(x), x.upper()

print sorted(strings, key=mykey)
Task: Animation


C++: #include "animationwidget.h"

#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>

#include <algorithm>

AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
    setWindowTitle(tr("Animation"));
    QFont font("Courier", 24);
    QLabel* label = new QLabel("Hello World! ");
    label->setFont(font);
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addWidget(label);
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [label,this]() {
        QString text = label->text();
        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
        label->setText(text);
    });
    timer->start(200);
}

void AnimationWidget::mousePressEvent(QMouseEvent*) {
    right_ = !right_;
}






Python: txt = "Hello, world! "
left = True

def draw():
    global txt
    background(128)
    text(txt, 10, height / 2)
    if frameCount % 10 == 0:
        if (left):
            txt = rotate(txt, 1)
        else:
            txt = rotate(txt, -1)
        println(txt)

def mouseReleased():
    global left
    left = not left

def rotate(text, startIdx):
    rotated = text[startIdx:] + text[:startIdx]
    return rotated
Task: Sorting algorithms_Radix sort


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


class radix_test
{
    const int bit; 
public:
    radix_test(int offset) : bit(offset) {} 

    bool operator()(int value) const 
    {
        if (bit == 31) 
            return value < 0; 
        else
            return !(value & (1 << bit)); 
    }
};


void lsd_radix_sort(int *first, int *last)
{
    for (int lsb = 0; lsb < 32; ++lsb) 
    {
        std::stable_partition(first, last, radix_test(lsb));
    }
}


void msd_radix_sort(int *first, int *last, int msb = 31)
{
    if (first != last && msb >= 0)
    {
        int *mid = std::partition(first, last, radix_test(msb));
        msb--; 
        msd_radix_sort(first, mid, msb); 
        msd_radix_sort(mid, last, msb); 
    }
}


int main()
{
    int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };

    lsd_radix_sort(data, data + 8);
    

    std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));

    return 0;
}






Python: 
from math import log
 
def getDigit(num, base, digit_num):
    
    return (num // base ** digit_num) % base  
 
def makeBlanks(size):
    
    return [ [] for i in range(size) ]  
 
def split(a_list, base, digit_num):
    buckets = makeBlanks(base)
    for num in a_list:
        
        buckets[getDigit(num, base, digit_num)].append(num)  
    return buckets
 

def merge(a_list):
    new_list = []
    for sublist in a_list:
       new_list.extend(sublist)
    return new_list
 
def maxAbs(a_list):
    
    return max(abs(num) for num in a_list)

def split_by_sign(a_list):
    
    
    buckets = [[], []]
    for num in a_list:
        if num < 0:
            buckets[0].append(num)
        else:
            buckets[1].append(num)
    return buckets
 
def radixSort(a_list, base):
    
    passes = int(round(log(maxAbs(a_list), base)) + 1) 
    new_list = list(a_list)
    for digit_num in range(passes):
        new_list = merge(split(new_list, base, digit_num))
    return merge(split_by_sign(new_list))
Task: List comprehensions


C++: #include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <iterator>

void list_comprehension( std::vector<int> & , int ) ;

int main( ) {
   std::vector<int> triangles ;
   list_comprehension( triangles , 20 ) ;
   std::copy( triangles.begin( ) , triangles.end( ) ,
	 std::ostream_iterator<int>( std::cout , " " ) ) ;
   std::cout << std::endl ;
   return 0 ;
}

void list_comprehension( std::vector<int> & numbers , int upper_border ) {
   for ( int a = 1 ; a < upper_border ; a++ ) {
      for ( int b = a + 1 ; b < upper_border ; b++ ) {
	 double c = pow( a * a + b * b , 0.5 ) ; 
	 if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) {
	    if ( c == floor( c ) ) {
	       numbers.push_back( a ) ;
	       numbers.push_back( b ) ;	      
	       numbers.push_back( static_cast<int>( c ) ) ;
	    }
	 }
      }
   }
}






Python: [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
Task: Sorting algorithms_Selection sort


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

template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
                                                       ForwardIterator end) {
  for(auto i = begin; i != end; ++i) {
    std::iter_swap(i, std::min_element(i, end));
  }
}

int main() {
  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
  selection_sort(std::begin(a), std::end(a));
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}






Python: def selection_sort(lst):
    for i, e in enumerate(lst):
        mn = min(range(i,len(lst)), key=lst.__getitem__)
        lst[i], lst[mn] = lst[mn], e
    return lst