WeixiangYan/CodeTransOcean huggingface dataset:
Task: List rooted trees


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

std::vector<long> TREE_LIST;
std::vector<int> OFFSET;

void init() {
    for (size_t i = 0; i < 32; i++) {
        if (i == 1) {
            OFFSET.push_back(1);
        } else {
            OFFSET.push_back(0);
        }
    }
}

void append(long t) {
    TREE_LIST.push_back(1 | (t << 1));
}

void show(long t, int l) {
    while (l-- > 0) {
        if (t % 2 == 1) {
            std::cout << '(';
        } else {
            std::cout << ')';
        }
        t = t >> 1;
    }
}

void listTrees(int n) {
    for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) {
        show(TREE_LIST[i], 2 * n);
        std::cout << '\n';
    }
}

void assemble(int n, long t, int sl, int pos, int rem) {
    if (rem == 0) {
        append(t);
        return;
    }

    auto pp = pos;
    auto ss = sl;

    if (sl > rem) {
        ss = rem;
        pp = OFFSET[ss];
    } else if (pp >= OFFSET[ss + 1]) {
        ss--;
        if (ss == 0) {
            return;
        }
        pp = OFFSET[ss];
    }

    assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss);
    assemble(n, t, ss, pp + 1, rem);
}

void makeTrees(int n) {
    if (OFFSET[n + 1] != 0) {
        return;
    }
    if (n > 0) {
        makeTrees(n - 1);
    }
    assemble(n, 0, n - 1, OFFSET[n - 1], n - 1);
    OFFSET[n + 1] = TREE_LIST.size();
}

void test(int n) {
    if (n < 1 || n > 12) {
        throw std::runtime_error("Argument must be between 1 and 12");
    }

    append(0);

    makeTrees(n);
    std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n';
    listTrees(n);
}

int main() {
    init();
    test(5);

    return 0;
}






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

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

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

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


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

for x in bags(5): print(replace_brackets(x[1]))
Task: Longest common suffix


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

std::string lcs(const std::vector<std::string>& strs) {
    std::vector<std::string::const_reverse_iterator> backs;
    std::string s;
    
    if (strs.size() == 0) return "";
    if (strs.size() == 1) return strs[0];
    
    for (auto& str : strs) backs.push_back(str.crbegin());
    
    while (backs[0] != strs[0].crend()) {
        char ch = *backs[0]++;
        for (std::size_t i = 1; i<strs.size(); i++) {
            if (backs[i] == strs[i].crend()) goto done;
            if (*backs[i] != ch) goto done;
            backs[i]++;
        }
        s.push_back(ch);
    }
    
done:
    reverse(s.begin(), s.end());
    return s;
}

void test(const std::vector<std::string>& strs) {
    std::cout << "[";
    for (std::size_t i = 0; i<strs.size(); i++) {
        std::cout << '"' << strs[i] << '"';
        if (i != strs.size()-1) std::cout << ", ";
    }
    std::cout << "] -> `" << lcs(strs) << "`\n";
}

int main() {
    std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
    std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
    std::vector<std::string> t3 = 
        {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
    std::vector<std::string> t4 = {"longest", "common", "suffix"};
    std::vector<std::string> t5 = {""};
    std::vector<std::string> t6 = {};
    std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};

    std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
    
    for (auto t : tests) test(t);
    return 0;
}






Python: 

from itertools import takewhile
from functools import reduce



def longestCommonSuffix(xs):
    
    def allSame(cs):
        h = cs[0]
        return all(h == c for c in cs[1:])

    def firstCharPrepended(s, cs):
        return cs[0] + s
    return reduce(
        firstCharPrepended,
        takewhile(
            allSame,
            zip(*(reversed(x) for x in xs))
        ),
        ''
    )




def main():
    

    samples = [
        [
            "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"
        ], [
            "Sondag", "Maandag", "Dinsdag", "Woensdag",
            "Donderdag", "Vrydag", "Saterdag"
        ]
    ]
    for xs in samples:
        print(
            longestCommonSuffix(xs)
        )



if __name__ == '__main__':
    main()
Task: Sum of elements below main diagonal of matrix


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

template<typename T>
T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {
    T sum = 0;
    for (std::size_t y = 0; y < matrix.size(); y++)
        for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)
            sum += matrix[y][x];
    return sum;
}

int main() {
    std::vector<std::vector<int>> matrix = {
        {1,3,7,8,10},
        {2,4,16,14,4},
        {3,1,9,18,11},
        {12,14,17,18,20},
        {7,1,3,9,5}
    };
    
    std::cout << sum_below_diagonal(matrix) << std::endl;
    return 0;
}






Python: from numpy import array, tril, sum

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

print(sum(tril(A, -1)))
Task: FASTA format


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

int main( int argc, char **argv ){
    if( argc <= 1 ){
        std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl;
        return -1;
    }

    std::ifstream input(argv[1]);
    if(!input.good()){
        std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl;
        return -1;
    }

    std::string line, name, content;
    while( std::getline( input, line ).good() ){
        if( line.empty() || line[0] == '>' ){ 
            if( !name.empty() ){ 
                std::cout << name << " : " << content << std::endl;
                name.clear();
            }
            if( !line.empty() ){
                name = line.substr(1);
            }
            content.clear();
        } else if( !name.empty() ){
            if( line.find(' ') != std::string::npos ){ 
                name.clear();
                content.clear();
            } else {
                content += line;
            }
        }
    }
    if( !name.empty() ){ 
        std::cout << name << " : " << content << std::endl;
    }
    
    return 0;
}






Python: import io

FASTA=

infile = io.StringIO(FASTA)

def fasta_parse(infile):
    key = ''
    for line in infile:
        if line.startswith('>'):
            if key:
                yield key, val
            key, val = line[1:].rstrip().split()[0], ''
        elif key:
            val += line.rstrip()
    if key:
        yield key, val

print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Task: Elementary cellular automaton_Random number generator


C++: #include <bitset>
#include <stdio.h>

#define SIZE	           80
#define RULE               30
#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))

void evolve(std::bitset<SIZE> &s) {
    int i;
    std::bitset<SIZE> t(0);
    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );
    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );
    for (i = 1; i < SIZE-1; i++)
	t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );
    for (i = 0; i < SIZE; i++) s[i] = t[i];
}
void show(std::bitset<SIZE> s) {
    int i;
    for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' ');
    printf("|\n");
}
unsigned char byte(std::bitset<SIZE> &s) {
    unsigned char b = 0;
    int i;
    for (i=8; i--; ) {
	b |= s[0] << i; 
	evolve(s);
    }
    return b;
}

int main() {
    int i;
    std::bitset<SIZE> state(1);
    for (i=10; i--; )
	printf("%u%c", byte(state), i ? ' ' : '\n');
    return 0;
}






Python: from elementary_cellular_automaton import eca, eca_wrap

def rule30bytes(lencells=100):
    cells = '1' + '0' * (lencells - 1)
    gen = eca(cells, 30)
    while True:
        yield int(''.join(next(gen)[0] for i in range(8)), 2)

if __name__ == '__main__':
    print([b for i,b in zip(range(10), rule30bytes())])
Task: Pseudo-random numbers_PCG32


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

class PCG32 {
private:
    const uint64_t N = 6364136223846793005;
    uint64_t state = 0x853c49e6748fea9b;
    uint64_t inc = 0xda3e39cb94b95bdb;
public:
    uint32_t nextInt() {
        uint64_t old = state;
        state = old * N + inc;
        uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27);
        uint32_t rot = old >> 59;
        return (shifted >> rot) | (shifted << ((~rot + 1) & 31));
    }

    double nextFloat() {
        return ((double)nextInt()) / (1LL << 32);
    }

    void seed(uint64_t seed_state, uint64_t seed_sequence) {
        state = 0;
        inc = (seed_sequence << 1) | 1;
        nextInt();
        state = state + seed_state;
        nextInt();
    }
};

int main() {
    auto r = new PCG32();

    r->seed(42, 54);
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << r->nextInt() << '\n';
    std::cout << '\n';

    std::array<int, 5> counts{ 0, 0, 0, 0, 0 };
    r->seed(987654321, 1);
    for (size_t i = 0; i < 100000; i++) {
        int j = (int)floor(r->nextFloat() * 5.0);
        counts[j]++;
    }

    std::cout << "The counts for 100,000 repetitions are:\n";
    for (size_t i = 0; i < counts.size(); i++) {
        std::cout << "  " << i << " : " << counts[i] << '\n';
    }

    return 0;
}






Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005


class PCG32():
    
    def __init__(self, seed_state=None, seed_sequence=None):
        if all(type(x) == int for x in (seed_state, seed_sequence)):
            self.seed(seed_state, seed_sequence)
        else:
            self.state = self.inc = 0
    
    def seed(self, seed_state, seed_sequence):
        self.state = 0
        self.inc = ((seed_sequence << 1) | 1) & mask64
        self.next_int()
        self.state = (self.state + seed_state)
        self.next_int()
        
    def next_int(self):
        "return random 32 bit unsigned int"
        old = self.state
        self.state = ((old * CONST) + self.inc) & mask64
        xorshifted = (((old >> 18) ^ old) >> 27) & mask32
        rot = (old >> 59) & mask32
        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
        answer = answer &mask32
        
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = PCG32()
    random_gen.seed(42, 54)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321, 1)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Rep-string


C++: #include <string>
#include <vector>
#include <boost/regex.hpp>

bool is_repstring( const std::string & teststring , std::string & repunit ) {
   std::string regex( "^(.+)\\1+(.*)$" ) ;
   boost::regex e ( regex ) ;
   boost::smatch what ;
   if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
      std::string firstbracket( what[1 ] ) ;
      std::string secondbracket( what[ 2 ] ) ;
      if ( firstbracket.length( ) >= secondbracket.length( ) &&
	    firstbracket.find( secondbracket ) != std::string::npos ) {
	 repunit = firstbracket  ;
      }
   }
   return !repunit.empty( ) ;
}

int main( ) {
   std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" ,
      "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ;
   std::string theRep ;
   for ( std::string myString : teststrings ) {
      if ( is_repstring( myString , theRep ) ) {
	 std::cout << myString << " is a rep string! Here is a repeating string:\n" ;
	 std::cout << theRep << " " ;
      }
      else {
	 std::cout << myString << " is no rep string!" ;
      }
      theRep.clear( ) ;
      std::cout << std::endl ;
   }
   return 0 ;
}






Python: def is_repeated(text):
    'check if the first part of the string is repeated throughout the string'
    for x in range(len(text)//2, 0, -1):
        if text.startswith(text[x:]): return x
    return 0

matchstr = 
for line in matchstr.split():
    ln = is_repeated(line)
    print('%r has a repetition length of %i i.e. %s' 
           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))
Task: Literals_String


C++: auto strA = R"(this is
a newline-separated
raw string)";






Python: 'c' == "c" 
'text' == "text"
' " '
" ' "
'\x20' == ' '
u'unicode string'
u'\u05d0'
Task: Changeable words


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

int hamming_distance(const std::string& str1, const std::string& str2) {
    size_t len1 = str1.size();
    size_t len2 = str2.size();
    if (len1 != len2)
        return 0;
    int count = 0;
    for (size_t i = 0; i < len1; ++i) {
        if (str1[i] != str2[i])
            ++count;
        
        if (count == 2)
            break;
    }
    return count;
}

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 line;
    std::vector<std::string> dictionary;
    while (getline(in, line)) {
        if (line.size() > 11)
            dictionary.push_back(line);
    }
    std::cout << "Changeable words in " << filename << ":\n";
    int n = 1;
    for (const std::string& word1 : dictionary) {
        for (const std::string& word2 : dictionary) {
            if (hamming_distance(word1, word2) == 1)
                std::cout << std::setw(2) << std::right << n++
                    << ": " << std::setw(14) << std::left << word1
                    << " -> " << word2 << '\n';
        }
    }
    return EXIT_SUCCESS;
}






Python: from collections import defaultdict, Counter


def getwords(minlength=11, fname='unixdict.txt'):
    "Return set of lowercased words of > given number of characters"
    with open(fname) as f:
        words = f.read().strip().lower().split()
    return {w for w in words if len(w) > minlength}

words11 = getwords()
word_minus_1 = defaultdict(list)    
minus_1_to_word = defaultdict(list) 

for w in words11:
    for i in range(len(w)):
        minus_1 = w[:i] + w[i+1:]
        word_minus_1[minus_1].append((w, i))   
        if minus_1 in words11:
            minus_1_to_word[minus_1].append(w)
    
cwords = set()  
for _, v in word_minus_1.items():
    if len(v) >1:
        change_indices = Counter(i for wrd, i in v)
        change_words = set(wrd for wrd, i in v)
        words_changed = None
        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
            words_changed = [wrd for wrd, i in v
                             if change_indices[i] > 1]
        if words_changed:
            cwords.add(tuple(sorted(words_changed)))

print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
    print(f"  {k:12} From {', '.join(v)}")

print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
    print(f"  {v[0]:12} From {', '.join(v[1:])}")
Task: Monads_List monad


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

using namespace std;


template <typename T>
auto operator>>(const vector<T>& monad, auto f)
{
    
    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;
    for(auto& item : monad)
    {
        
        
        const auto r = f(item);
        
        result.insert(result.end(), begin(r), end(r));
    }
    
    return result;
}


auto Pure(auto t)
{
    return vector{t};
}


auto Double(int i)
{
    return Pure(2 * i);
}


auto Increment(int i)
{
    return Pure(i + 1);
}


auto NiceNumber(int i)
{
    return Pure(to_string(i) + " is a nice number\n");
}



auto UpperSequence = [](auto startingVal)
{
    const int MaxValue = 500;
    vector<decltype(startingVal)> sequence;
    while(startingVal <= MaxValue) 
        sequence.push_back(startingVal++);
    return sequence;
};


void PrintVector(const auto& vec)
{
    cout << " ";
    for(auto value : vec)
    {
        cout << value << " ";
    }
    cout << "\n";
}


void PrintTriples(const auto& vec)
{
    cout << "Pythagorean triples:\n";
    for(auto it = vec.begin(); it != vec.end();)
    {
        auto x = *it++;
        auto y = *it++;
        auto z = *it++;
        
        cout << x << ", " << y << ", " << z << "\n";
    }
    cout << "\n";
}

int main()
{
    
    auto listMonad = 
        vector<int> {2, 3, 4} >> 
        Increment >> 
        Double >>
        NiceNumber;
        
    PrintVector(listMonad);
    
    
    
    
    
    auto pythagoreanTriples = UpperSequence(1) >> 
        [](int x){return UpperSequence(x) >>
        [x](int y){return UpperSequence(y) >>
        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};
    
    PrintTriples(pythagoreanTriples);
}






Python: 
from __future__ import annotations
from itertools import chain

from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar


T = TypeVar("T")


class MList(List[T]):
    @classmethod
    def unit(cls, value: Iterable[T]) -> MList[T]:
        return cls(value)

    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return MList(chain.from_iterable(map(func, self)))

    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return self.bind(func)


if __name__ == "__main__":
    
    print(
        MList([1, 99, 4])
        .bind(lambda val: MList([val + 1]))
        .bind(lambda val: MList([f"${val}.00"]))
    )

    
    print(
        MList([1, 99, 4])
        >> (lambda val: MList([val + 1]))
        >> (lambda val: MList([f"${val}.00"]))
    )

    
    print(
        MList(range(1, 6)).bind(
            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
        )
    )

    
    print(
        MList(range(1, 26)).bind(
            lambda x: MList(range(x + 1, 26)).bind(
                lambda y: MList(range(y + 1, 26)).bind(
                    lambda z: MList([(x, y, z)])
                    if x * x + y * y == z * z
                    else MList([])
                )
            )
        )
    )
Task: Getting the number of decimals


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

int findNumOfDec(double x) {
    std::stringstream ss;
    ss << std::fixed << std::setprecision(14) << x;

    auto s = ss.str();
    auto pos = s.find('.');
    if (pos == std::string::npos) {
        return 0;
    }

    auto tail = s.find_last_not_of('0');

    return tail - pos;
}

void test(double x) {
    std::cout << x << " has " << findNumOfDec(x) << " decimals\n";
}

int main() {
    test(12.0);
    test(12.345);
    test(12.345555555555);
    test(12.3450);
    test(12.34555555555555555555);
    test(1.2345e+54);
    return 0;
}






Python: In [6]: def dec(n):
   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0

In [7]: dec('12.345')
Out[7]: 3

In [8]: dec('12.3450')
Out[8]: 4

In [9]:
Task: Enumerations


C++: enum fruits { apple, banana, cherry };

enum fruits { apple = 0, banana = 1, cherry = 2 };






Python: >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>> 
>>> 
>>> class Contact2(Enum):
	FIRST_NAME = 1
	LAST_NAME = 2
	PHONE = 3

	
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
Task: Increasing gaps between consecutive Niven numbers


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



uint64_t digit_sum(uint64_t n, uint64_t sum) {
    ++sum;
    while (n > 0 && n % 10 == 0) {
        sum -= 9;
        n /= 10;
    }
    return sum;
}

inline bool divisible(uint64_t n, uint64_t d) {
    if ((d & 1) == 0 && (n & 1) == 1)
        return false;
    return n % d == 0;
}

int main() {
    
    std::cout.imbue(std::locale(""));

    uint64_t previous = 1, gap = 0, sum = 0;
    int niven_index = 0, gap_index = 1;

    std::cout << "Gap index  Gap    Niven index    Niven number\n";
    for (uint64_t niven = 1; gap_index <= 32; ++niven) {
        sum = digit_sum(niven, sum);
        if (divisible(niven, sum)) {
            if (niven > previous + gap) {
                gap = niven - previous;
                std::cout << std::setw(9) << gap_index++
                    << std::setw(5) << gap
                    << std::setw(15) << niven_index
                    << std::setw(16) << previous << '\n';
            }
            previous = niven;
            ++niven_index;
        }
    }
    return 0;
}






Python: 





def digit_sum(n, sum):
    sum += 1
    while n > 0 and n % 10 == 0:
        sum -= 9
        n /= 10
    
    return sum
    
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
 
print("Gap index  Gap    Niven index    Niven number")

niven = 1

while gap_index <= 22:
    sum = digit_sum(niven, sum)
    if niven % sum == 0:
        if niven > previous + gap:
            gap = niven - previous;
            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))
            gap_index += 1
        previous = niven
        niven_index += 1
    niven += 1
Task: Print debugging statement


C++: #include <iostream>


#define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__)



int main() {
    DEBUG("Hello world");
    DEBUG("Some %d Things", 42);

    return 0;
}






Python: import logging, logging.handlers

LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG


def print_squares(number):
    logger.info("In print_squares")
    for i in range(number):
        print("square of {0} is {1}".format(i , i*i))
        logger.debug(f'square of {i} is {i*i}')

def print_cubes(number):
    logger.info("In print_cubes")
    for j in range(number):
        print("cube of {0} is {1}".format(j, j*j*j))
        logger.debug(f'cube of {j} is {j*j*j}')

if __name__ == "__main__":

    logger = logging.getLogger("logdemo")
    logger.setLevel(LOGLEVEL)
    handler = logging.FileHandler(LOG_FILENAME)
    handler.setFormatter(logging.Formatter(FORMAT_STRING))
    logger.addHandler(handler)

    print_squares(10)
    print_cubes(10)

    logger.info("All done")