WeixiangYan/CodeTransOcean huggingface dataset:
Task: Tree from nesting levels


C++: #include <any>
#include <iostream>
#include <iterator>
#include <vector>

using namespace std;


vector<any> MakeTree(input_iterator auto first, input_iterator auto last, int depth = 1)
{
    vector<any> tree;
    while (first < last && depth <= *first)
    {
        if(*first == depth)
        {
            
            tree.push_back(*first);
            ++first;
        }
        else 
        {
            
            tree.push_back(MakeTree(first, last, depth + 1));
            first = find(first + 1, last, depth); 
        }
    }
        
    return tree;
}


void PrintTree(input_iterator auto first, input_iterator auto last)
{
    cout << "[";
    for(auto it = first; it != last; ++it)
    {
        if(it != first) cout << ", ";
        if constexpr (is_integral_v<remove_reference_t<decltype(*first)>>)
        {
            
            cout << *it;
        }
        else
        {
            
            if(it->type() == typeid(unsigned int))
            {
                
                cout << any_cast<unsigned int>(*it);
            }
            else
            {
                
                const auto& subTree = any_cast<vector<any>>(*it);
                PrintTree(subTree.begin(), subTree.end());
            }
        }
    }
    cout << "]";
}

int main(void) 
{
    auto execises = vector<vector<unsigned int>> {
        {},
        {1, 2, 4},
        {3, 1, 3, 1},
        {1, 2, 3, 1},
        {3, 2, 1, 3},
        {3, 3, 3, 1, 1, 3, 3, 3}
        };
    
    for(const auto& e : execises)
    {
        auto tree = MakeTree(e.begin(), e.end());
        PrintTree(e.begin(), e.end());
        cout << " Nests to:\n"; 
        PrintTree(tree.begin(), tree.end());
        cout << "\n\n";
    }
}






Python: def to_tree(x, index=0, depth=1):
   so_far = []
   while index < len(x):
       this = x[index]
       if this == depth:
           so_far.append(this)
       elif this > depth:
           index, deeper = to_tree(x, index, depth + 1)
           so_far.append(deeper)
       else: 
           index -=1
           break
       index += 1
   return (index, so_far) if depth > 1 else so_far


if __name__ ==  "__main__":
    from pprint import pformat

    def pnest(nest:list, width: int=9) -> str:
        text = pformat(nest, width=width).replace('\n', '\n    ')
        print(f" OR {text}\n")

    exercises = [
        [],
        [1, 2, 4],
        [3, 1, 3, 1],
        [1, 2, 3, 1],
        [3, 2, 1, 3],
        [3, 3, 3, 1, 1, 3, 3, 3],
        ]
    for flat in exercises:
        nest = to_tree(flat)
        print(f"{flat} NESTS TO: {nest}")
        pnest(nest)
Task: Sylvester's sequence


C++: #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>

using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;

integer sylvester_next(const integer& n) {
    return n * n - n + 1;
}

int main() {
    std::cout << "First 10 elements in Sylvester's sequence:\n";
    integer term = 2;
    rational sum = 0;
    for (int i = 1; i <= 10; ++i) {
        std::cout << std::setw(2) << i << ": " << term << '\n';
        sum += rational(1, term);
        term = sylvester_next(term);
    }
    std::cout << "Sum of reciprocals: " << sum << '\n';
}






Python: 

from functools import reduce
from itertools import count, islice



def sylvester():
    
    def go(n):
        return 1 + reduce(
            lambda a, x: a * go(x),
            range(0, n),
            1
        ) if 0 != n else 2

    return map(go, count(0))




def main():
    

    print("First 10 terms of OEIS A000058:")
    xs = list(islice(sylvester(), 10))
    print('\n'.join([
        str(x) for x in xs
    ]))

    print("\nSum of the reciprocals of the first 10 terms:")
    print(
        reduce(lambda a, x: a + 1 / x, xs, 0)
    )



if __name__ == '__main__':
    main()
Task: Here document


C++: #include <iostream> 

int main()
{
  std::cout <<
R"EOF(  A  raw  string  begins  with  R,  then a double-quote ("),  then an optional
identifier (here I've used "EOF"),  then an opening parenthesis ('(').  If you
use  an  identifier,  it  cannot  be longer than 16 characters,  and it cannot
contain a space,  either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.

  It  ends with a closing parenthesis (')'),  the identifer (if you used one),
and a double-quote.

  All  characters are okay in a raw string,  no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}






Python: print()
Task: Hash join


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

using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {

  {"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};

tab_t tab2 {

  {"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};

std::ostream& operator<<(std::ostream& o, const tab_t& t) {
  for(size_t i = 0; i < t.size(); ++i) {
    o << i << ":";
    for(const auto& e : t[i]) 
      o << '\t' << e;
    o << std::endl;
  }
  return o;
}

tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
  std::unordered_multimap<std::string, size_t> hashmap;
  
  for(size_t i = 0; i < a.size(); ++i) {
    hashmap.insert(std::make_pair(a[i][columna], i));
  }
  
  tab_t result;
  for(size_t i = 0; i < b.size(); ++i) {
    auto range = hashmap.equal_range(b[i][columnb]);
    for(auto it = range.first; it != range.second; ++it) {
      tab_t::value_type row;
      row.insert(row.end() , a[it->second].begin() , a[it->second].end());
      row.insert(row.end() , b[i].begin()          , b[i].end());
      result.push_back(std::move(row));
    }
  }
  return result;
}

int main(int argc, char const *argv[])
{
  using namespace std;
  int ret = 0;
  cout << "Table A: "       << endl << tab1 << endl;
  cout << "Table B: "       << endl << tab2 << endl;
  auto tab3 = Join(tab1, 1, tab2, 0);
  cout << "Joined tables: " << endl << tab3 << endl;
  return ret;
}






Python: from collections import defaultdict

def hashJoin(table1, index1, table2, index2):
    h = defaultdict(list)
    
    for s in table1:
        h[s[index1]].append(s)
    
    return [(s, r) for r in table2 for s in h[r[index2]]]

table1 = [(27, "Jonah"),
          (18, "Alan"),
          (28, "Glory"),
          (18, "Popeye"),
          (28, "Alan")]
table2 = [("Jonah", "Whales"),
          ("Jonah", "Spiders"),
          ("Alan", "Ghosts"),
          ("Alan", "Zombies"),
          ("Glory", "Buffy")]

for row in hashJoin(table1, 1, table2, 0):
    print(row)
Task: Odd squarefree semiprimes


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

bool odd_square_free_semiprime(int n) {
    if ((n & 1) == 0)
        return false;
    int count = 0;
    for (int i = 3; i * i <= n; i += 2) {
        for (; n % i == 0; n /= i) {
            if (++count > 1)
                return false;
        }
    }
    return count == 1;
}

int main() {
    const int n = 1000;
    std::cout << "Odd square-free semiprimes < " << n << ":\n";
    int count = 0;
    for (int i = 1; i < n; i += 2) {
        if (odd_square_free_semiprime(i)) {
            ++count;
            std::cout << std::setw(4) << i;
            if (count % 20 == 0)
                std::cout << '\n';
        }
    }
    std::cout << "\nCount: " << count << '\n';
    return 0;
}






Python: 

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


if __name__ == '__main__':
    for p in range(3, 999):
        if not isPrime(p):            
            continue
        for q in range(p+1, 1000//p):
            if not isPrime(q):
                continue
            print(p*q, end = " ");
Task: Sierpinski curve


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

class sierpinski_curve {
public:
    void write(std::ostream& out, int size, int length, int order);
private:
    static std::string rewrite(const std::string& s);
    void line(std::ostream& out);
    void execute(std::ostream& out, const std::string& s);
    double x_;
    double y_;
    int angle_;
    int length_;
};

void sierpinski_curve::write(std::ostream& out, int size, int length, int order) {
    length_ = length;
    x_ = length/std::sqrt(2.0);
    y_ = 2 * x_;
    angle_ = 45;
    out << "<svg xmlns='http:
        << size << "' height='" << size << "'>\n";
    out << "<rect width='100%' height='100%' fill='white'/>\n";
    out << "<path stroke-width='1' stroke='black' fill='none' d='";
    std::string s = "F--XF--F--XF";
    for (int i = 0; i < order; ++i)
        s = rewrite(s);
    execute(out, s);
    out << "'/>\n</svg>\n";
}

std::string sierpinski_curve::rewrite(const std::string& s) {
    std::string t;
    for (char c : s) {
        if (c == 'X')
            t += "XF+G+XF--F--XF+G+X";
        else
            t += c;
    }
    return t;
}

void sierpinski_curve::line(std::ostream& out) {
    double theta = (3.14159265359 * angle_)/180.0;
    x_ += length_ * std::cos(theta);
    y_ -= length_ * std::sin(theta);
    out << " L" << x_ << ',' << y_;
}

void sierpinski_curve::execute(std::ostream& out, const std::string& s) {
    out << 'M' << x_ << ',' << y_;
    for (char c : s) {
        switch (c) {
        case 'F':
        case 'G':
            line(out);
            break;
        case '+':
            angle_ = (angle_ + 45) % 360;
            break;
        case '-':
            angle_ = (angle_ - 45) % 360;
            break;
        }
    }
}

int main() {
    std::ofstream out("sierpinski_curve.svg");
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return 1;
    }
    sierpinski_curve s;
    s.write(out, 545, 7, 5);
    return 0;
}






Python: import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb as hsv

def curve(axiom, rules, angle, depth):
    for _ in range(depth):
        axiom = ''.join(rules[c] if c in rules else c for c in axiom)

    a, x, y = 0, [0], [0]
    for c in axiom:
        match c:
            case '+':
                a += 1
            case '-':
                a -= 1
            case 'F' | 'G':
                x.append(x[-1] + np.cos(a*angle*np.pi/180))
                y.append(y[-1] + np.sin(a*angle*np.pi/180))

    l = len(x)
    
    for i in range(l - 1):
        plt.plot(x[i:i+2], y[i:i+2], color=hsv([i/l, 1, .7]))
    plt.gca().set_aspect(1)
    plt.show()

curve('F--XF--F--XF', {'X': 'XF+G+XF--F--XF+G+X'}, 45, 5)
Task: Most frequent k chars distance


C++: #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
#include <sstream>

std::string mostFreqKHashing ( const std::string & input , int k ) {
   std::ostringstream oss ;
   std::map<char, int> frequencies ;
   for ( char c : input ) {
      frequencies[ c ] = std::count ( input.begin( ) , input.end( ) , c ) ;
   }
   std::vector<std::pair<char , int>> letters ( frequencies.begin( ) , frequencies.end( ) ) ;
   std::sort ( letters.begin( ) , letters.end( ) , [input] ( std::pair<char, int> a ,
	         std::pair<char, int> b ) { char fc = std::get<0>( a ) ; char fs = std::get<0>( b ) ; 
	         int o = std::get<1>( a ) ; int p = std::get<1>( b ) ; if ( o != p ) { return o > p ; }
	         else { return input.find_first_of( fc ) < input.find_first_of ( fs ) ; } } ) ;
   for ( int i = 0 ; i < letters.size( ) ; i++ ) {
      oss << std::get<0>( letters[ i ] ) ;
      oss << std::get<1>( letters[ i ] ) ;
   }
   std::string output ( oss.str( ).substr( 0 , 2 * k ) ) ;
   if ( letters.size( ) >= k ) {
      return output ;
   }
   else {
      return output.append( "NULL0" ) ;
   }
}

int mostFreqKSimilarity ( const std::string & first , const std::string & second ) {
   int i = 0 ;
   while ( i < first.length( ) - 1  ) {
      auto found = second.find_first_of( first.substr( i , 2 ) ) ;
      if ( found != std::string::npos ) 
	 return std::stoi ( first.substr( i , 2 )) ;
      else 
	 i += 2 ;
   }
   return 0 ;
}

int mostFreqKSDF ( const std::string & firstSeq , const std::string & secondSeq , int num ) {
   return mostFreqKSimilarity ( mostFreqKHashing( firstSeq , num ) , mostFreqKHashing( secondSeq , num ) ) ;
}

int main( ) {
   std::string s1("LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV" ) ;
   std::string s2( "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG" ) ;
   std::cout << "MostFreqKHashing( s1 , 2 ) = " << mostFreqKHashing( s1 , 2 ) << '\n' ;
   std::cout << "MostFreqKHashing( s2 , 2 ) = " << mostFreqKHashing( s2 , 2 ) << '\n' ;
   return 0 ;
}






Python: import collections
def MostFreqKHashing(inputString, K):
    occuDict = collections.defaultdict(int)
    for c in inputString:
        occuDict[c] += 1
    occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)
    outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])
    return outputStr 


def MostFreqKSimilarity(inputStr1, inputStr2):
    similarity = 0
    for i in range(0, len(inputStr1), 2):
        c = inputStr1[i]
        cnt1 = int(inputStr1[i + 1])
        for j in range(0, len(inputStr2), 2):
            if inputStr2[j] == c:
                cnt2 = int(inputStr2[j + 1])
                similarity += cnt1 + cnt2
                break
    return similarity

def MostFreqKSDF(inputStr1, inputStr2, K, maxDistance):
    return maxDistance - MostFreqKSimilarity(MostFreqKHashing(inputStr1,K), MostFreqKHashing(inputStr2,K))
Task: Find words which contains all the vowels


C++: #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>

bool contains_all_vowels_once(const std::string& word) {
    std::bitset<5> vowels;
    for (char ch : word) {
        ch = std::tolower(static_cast<unsigned char>(ch));
        size_t bit = 0;
        switch (ch) {
        case 'a': bit = 0; break;
        case 'e': bit = 1; break;
        case 'i': bit = 2; break;
        case 'o': bit = 3; break;
        case 'u': bit = 4; break;
        default: continue;
        }
        if (vowels.test(bit))
            return false;
        vowels.set(bit);
    }
    return vowels.all();
}

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    int n = 0;
    while (getline(in, word)) {
        if (word.size() > 10 && contains_all_vowels_once(word))
            std::cout << std::setw(2) << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}






Python: import urllib.request
from collections import Counter

urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>10:
        frequency = Counter(word.lower())
        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:
            print(word)
Task: Base 16 numbers needing a to f


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



bool nondecimal(unsigned int n) {
    for (; n > 0; n >>= 4) {
        if ((n & 0xF) > 9)
            return true;
    }
    return false;
}

int main() {
    unsigned int count = 0;
    for (unsigned int n = 0; n < 501; ++n) {
        if (nondecimal(n)) {
            ++count;
            std::cout << std::setw(3) << n << (count % 15 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\n\n" << count << " such numbers found.\n";
}






Python: 



def p(n):
    
    return 9 < n and (9 < n % 16 or p(n // 16))




def main():
    
    xs = [
        str(n) for n in range(1, 1 + 500)
        if p(n)
    ]
    print(f'{len(xs)} matches for the predicate:\n')
    print(
        table(6)(xs)
    )





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



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



if __name__ == '__main__':
    main()
Task: Juggler sequence


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

#include <gmpxx.h>

using big_int = mpz_class;

auto juggler(int n) {
    assert(n >= 1);
    int count = 0, max_count = 0;
    big_int a = n, max = n;
    while (a != 1) {
        if (a % 2 == 0)
            a = sqrt(a);
        else
            a = sqrt(big_int(a * a * a));
        ++count;
        if (a > max) {
            max = a;
            max_count = count;
        }
    }
    return std::make_tuple(count, max_count, max, max.get_str().size());
}

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << "n    l[n]  i[n]   h[n]\n";
    std::cout << "--------------------------------\n";
    for (int n = 20; n < 40; ++n) {
        auto [count, max_count, max, digits] = juggler(n);
        std::cout << std::setw(2) << n << "    " << std::setw(2) << count
                  << "    " << std::setw(2) << max_count << "    " << max
                  << '\n';
    }
    std::cout << '\n';
    std::cout << "       n       l[n]   i[n]   d[n]\n";
    std::cout << "----------------------------------------\n";
    for (int n : {113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443,
                  275485, 1267909, 2264915, 5812827, 7110201, 56261531,
                  92502777, 172376627, 604398963}) {
        auto [count, max_count, max, digits] = juggler(n);
        std::cout << std::setw(11) << n << "    " << std::setw(3) << count
                  << "    " << std::setw(3) << max_count << "    " << digits
                  << '\n';
    }
}






Python: from math import isqrt

def juggler(k, countdig=True, maxiters=1000):
    m, maxj, maxjpos = k, k, 0
    for i in range(1, maxiters):
        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
        if m >= maxj:
            maxj, maxjpos  = m, i
        if m == 1:
            print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
            return i

    print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")


print("       n    l(n)  i(n)       h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
    juggler(k, False)

for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
    juggler(k)
Task: Sierpinski square curve


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

class sierpinski_square {
public:
    void write(std::ostream& out, int size, int length, int order);
private:
    static std::string rewrite(const std::string& s);
    void line(std::ostream& out);
    void execute(std::ostream& out, const std::string& s);
    double x_;
    double y_;
    int angle_;
    int length_;
};

void sierpinski_square::write(std::ostream& out, int size, int length, int order) {
    length_ = length;
    x_ = (size - length)/2;
    y_ = length;
    angle_ = 0;
    out << "<svg xmlns='http:
        << size << "' height='" << size << "'>\n";
    out << "<rect width='100%' height='100%' fill='white'/>\n";
    out << "<path stroke-width='1' stroke='black' fill='none' d='";
    std::string s = "F+XF+F+XF";
    for (int i = 0; i < order; ++i)
        s = rewrite(s);
    execute(out, s);
    out << "'/>\n</svg>\n";
}

std::string sierpinski_square::rewrite(const std::string& s) {
    std::string t;
    for (char c : s) {
        if (c == 'X')
            t += "XF-F+F-XF+F+XF-F+F-X";
        else
            t += c;
    }
    return t;
}

void sierpinski_square::line(std::ostream& out) {
    double theta = (3.14159265359 * angle_)/180.0;
    x_ += length_ * std::cos(theta);
    y_ += length_ * std::sin(theta);
    out << " L" << x_ << ',' << y_;
}

void sierpinski_square::execute(std::ostream& out, const std::string& s) {
    out << 'M' << x_ << ',' << y_;
    for (char c : s) {
        switch (c) {
        case 'F':
            line(out);
            break;
        case '+':
            angle_ = (angle_ + 90) % 360;
            break;
        case '-':
            angle_ = (angle_ - 90) % 360;
            break;
        }
    }
}

int main() {
    std::ofstream out("sierpinski_square.svg");
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return 1;
    }
    sierpinski_square s;
    s.write(out, 635, 5, 5);
    return 0;
}






Python: import matplotlib.pyplot as plt
import math


def nextPoint(x, y, angle):
    a = math.pi * angle / 180
    x2 = (int)(round(x + (1 * math.cos(a))))
    y2 = (int)(round(y + (1 * math.sin(a))))
    return x2, y2


def expand(axiom, rules, level):
    for l in range(0, level):
        a2 = ""
        for c in axiom:
            if c in rules:
                a2 += rules[c]
            else:
                a2 += c
        axiom = a2
    return axiom


def draw_lsystem(axiom, rules, angle, iterations):
    xp = [1]
    yp = [1]
    direction = 0
    for c in expand(axiom, rules, iterations):
        if c == "F":
            xn, yn = nextPoint(xp[-1], yp[-1], direction)
            xp.append(xn)
            yp.append(yn)
        elif c == "-":
            direction = direction - angle
            if direction < 0:
                direction = 360 + direction
        elif c == "+":
            direction = (direction + angle) % 360

    plt.plot(xp, yp)
    plt.show()


if __name__ == '__main__':
    
    s_axiom = "F+XF+F+XF"
    s_rules = {"X": "XF-F+F-XF+F+XF-F+F-X"}
    s_angle = 90

    draw_lsystem(s_axiom, s_rules, s_angle, 3)
Task: Fixed length records


C++: #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>

void reverse(std::istream& in, std::ostream& out) {
    constexpr size_t record_length = 80;
    char record[record_length];
    while (in.read(record, record_length)) {
        std::reverse(std::begin(record), std::end(record));
        out.write(record, record_length);
    }
    out.flush();
}

int main(int argc, char** argv) {
    std::ifstream in("infile.dat", std::ios_base::binary);
    if (!in) {
        std::cerr << "Cannot open input file\n";
        return EXIT_FAILURE;
    }
    std::ofstream out("outfile.dat", std::ios_base::binary);
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return EXIT_FAILURE;
    }
    try {
        in.exceptions(std::ios_base::badbit);
        out.exceptions(std::ios_base::badbit);
        reverse(in, out);
    } catch (const std::exception& ex) {
        std::cerr << "I/O error: " << ex.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}






Python: infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')

while True:
    onerecord = infile.read(80)
    if len(onerecord) < 80:
        break
    onerecordreversed = bytes(reversed(onerecord))
    outfile.write(onerecordreversed)

infile.close()
outfile.close()
Task: Find words whose first and last three letters are equal


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

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    int n = 0;
    while (getline(in, word)) {
        const size_t len = word.size();
        if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
            std::cout << ++n << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}






Python: import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>5 and word[:3].lower()==word[-3:].lower():
        print(word)