WeixiangYan/CodeTransOcean huggingface dataset:
Task: Exactly three adjacent 3 in lists




Go: package main

import "fmt"

func main() {
    lists := [][]int{
        {9, 3, 3, 3, 2, 1, 7, 8, 5},
        {5, 2, 9, 3, 3, 7, 8, 4, 1},
        {1, 4, 3, 6, 7, 3, 8, 3, 2},
        {1, 2, 3, 4, 5, 6, 7, 8, 9},
        {4, 6, 8, 7, 2, 3, 3, 3, 1},
        {3, 3, 3, 1, 2, 4, 5, 1, 3},
        {0, 3, 3, 3, 3, 7, 2, 2, 6},
        {3, 3, 3, 3, 3, 4, 4, 4, 4},
    }
    for d := 1; d <= 4; d++ {
        fmt.Printf("Exactly %d adjacent %d's:\n", d, d)
        for _, list := range lists {
            var indices []int
            for i, e := range list {
                if e == d {
                    indices = append(indices, i)
                }
            }
            adjacent := false
            if len(indices) == d {
                adjacent = true
                for i := 1; i < len(indices); i++ {
                    if indices[i]-indices[i-1] != 1 {
                        adjacent = false
                        break
                    }
                }
            }
            fmt.Printf("%v -> %t\n", list, adjacent)
        }
        fmt.Println()
    }
}




Python: 

from itertools import dropwhile, takewhile



def nnPeers(n):
    
    def p(x):
        return n == x

    def go(xs):
        fromFirstMatch = list(dropwhile(
            lambda v: not p(v),
            xs
        ))
        ns = list(takewhile(p, fromFirstMatch))
        rest = fromFirstMatch[len(ns):]

        return p(len(ns)) and (
            not any(p(x) for x in rest)
        )

    return go




def main():
    
    print(
        '\n'.join([
            f'{xs} -> {nnPeers(3)(xs)}' for xs in [
                [9, 3, 3, 3, 2, 1, 7, 8, 5],
                [5, 2, 9, 3, 3, 7, 8, 4, 1],
                [1, 4, 3, 6, 7, 3, 8, 3, 2],
                [1, 2, 3, 4, 5, 6, 7, 8, 9],
                [4, 6, 8, 7, 2, 3, 3, 3, 1]
            ]
        ])
    )



if __name__ == '__main__':
    main()
Task: Permutations by swapping




Go: package permute




func Iter(p []int) func() int {
    f := pf(len(p))
    return func() int {
        return f(p)
    }
}



func pf(n int) func([]int) int {
    sign := 1
    switch n {
    case 0, 1:
        return func([]int) (s int) {
            s = sign
            sign = 0
            return
        }
    default:
        p0 := pf(n - 1)
        i := n
        var d int
        return func(p []int) int {
            switch {
            case sign == 0:
            case i == n:
                i--
                sign = p0(p[:i])
                d = -1
            case i == 0:
                i++
                sign *= p0(p[1:])
                d = 1
                if sign == 0 {
                    p[0], p[1] = p[1], p[0]
                }
            default:
                p[i], p[i-1] = p[i-1], p[i]
                sign = -sign
                i += d
            }
            return sign
        }
    }
}




Python: from operator import itemgetter
 
DEBUG = False 
 
def spermutations(n):
    
    sign = 1
    p = [[i, 0 if i == 0 else -1] 
         for i in range(n)]
 
    if DEBUG: print ' 
    yield tuple(pp[0] for pp in p), sign
 
    while any(pp[1] for pp in p): 
        i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp[1]),
                           key=itemgetter(1))
        sign *= -1
        if d1 == -1:
            
            i2 = i1 - 1
            p[i1], p[i2] = p[i2], p[i1]
            
            
            
            if i2 == 0 or p[i2 - 1][0] > n1:
                
                p[i2][1] = 0
        elif d1 == 1:
            
            i2 = i1 + 1
            p[i1], p[i2] = p[i2], p[i1]
            
            
            
            if i2 == n - 1 or p[i2 + 1][0] > n1:
                
                p[i2][1] = 0
        if DEBUG: print ' 
        yield tuple(pp[0] for pp in p), sign
 
        for i3, pp in enumerate(p):
            n3, d3 = pp
            if n3 > n1:
                pp[1] = 1 if i3 < i2 else -1
                if DEBUG: print ' 
 
 
if __name__ == '__main__':
    from itertools import permutations
 
    for n in (3, 4):
        print '\nPermutations and sign of %i items' % n
        sp = set()
        for i in spermutations(n):
            sp.add(i[0])
            print('Perm: %r Sign: %2i' % i)
            
        
        p = set(permutations(range(n)))
        assert sp == p, 'Two methods of generating permutations do not agree'
Task: Minimum multiple of m where digital sum equals m




Go: package main

import "rcu"

func main() {
    var res []int
    for n := 1; n <= 70; n++ {
        m := 1
        for rcu.DigitSum(m*n, 10) != n {
            m++
        }
        res = append(res, m)
    }
    rcu.PrintTable(res, 7, 10, true)
}




Python: 

from itertools import count, islice



def a131382():
    
    return (
        elemIndex(x)(
            productDigitSums(x)
        ) for x in count(1)
    )



def productDigitSums(n):
    
    return (digitSum(n * x) for x in count(0))




def main():
    

    print(
        table(10)([
            str(x) for x in islice(
                a131382(),
                40
            )
        ])
    )





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 digitSum(n):
    
    return sum(int(x) for x in list(str(n)))



def elemIndex(x):
    
    def go(xs):
        try:
            return next(
                i for i, v in enumerate(xs) if x == v
            )
        except StopIteration:
            return 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: Pythagorean quadruples




Go: package main

import "fmt"

const (
    N = 2200
    N2 = N * N * 2
)

func main() {
    s  := 3 
    var s1, s2 int    
    var r  [N + 1]bool
    var ab [N2 + 1]bool

    for a := 1; a <= N; a++ {
        a2 := a * a
        for b := a; b <= N; b++ {
            ab[a2 + b * b] = true
        }
    }

    for c := 1; c <= N; c++ {
        s1 = s
        s += 2
        s2 = s
        for d := c + 1; d <= N; d++ {
            if ab[s1] {
                r[d] = true
            }
            s1 += s2
            s2 += 2
        }
    }

    for d := 1; d <= N; d++ {
        if !r[d] {
            fmt.Printf("%d ", d)
        }       
    }
    fmt.Println()
}




Python: def quad(top=2200):
    r = [False] * top
    ab = [False] * (top * 2)**2
    for a in range(1, top):
        for b in range(a, top):
            ab[a * a + b * b] = True
    s = 3
    for c in range(1, top):
        s1, s, s2 = s, s + 2, s + 2
        for d in range(c + 1, top):
            if ab[s1]:
                r[d] = True
            s1 += s2
            s2 += 2
    return [i for i, val in enumerate(r) if not val and i]
    
if __name__ == '__main__':
    n = 2200
    print(f"Those values of d in 1..{n} that can't be represented: {quad(n)}")
Task: Steady squares




Go: package main

import (
    "fmt"
    "rcu"
    "strconv"
    "strings"
)

func contains(list []int, s int) bool {
    for _, e := range list {
        if e == s {
            return true
        }
    }
    return false
}

func main() {
    fmt.Println("Steady squares under 10,000:")
    finalDigits := []int{1, 5, 6}
    for i := 1; i < 10000; i++ {
        if !contains(finalDigits, i%10) {
            continue
        }
        sq := i * i
        sqs := strconv.Itoa(sq)
        is := strconv.Itoa(i)
        if strings.HasSuffix(sqs, is) {
            fmt.Printf("%5s -> %10s\n", rcu.Commatize(i), rcu.Commatize(sq))
        }
    }
}




Python: print("working...")
print("Steady squares under 10.000 are:")
limit = 10000

for n in range(1,limit):
    nstr = str(n)
    nlen = len(nstr)
    square = str(pow(n,2))
    rn = square[-nlen:]
    if nstr == rn:
       print(str(n) + " " + str(square))

print("done...")
Task: Numbers in base 10 that are palindromic in bases 2, 4, and 16




Go: package main

import (
    "fmt"
    "rcu"
    "strconv"
)

func reverse(s string) string {
    chars := []rune(s)
    for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 {
        chars[i], chars[j] = chars[j], chars[i]
    }
    return string(chars)
}

func main() {
    fmt.Println("Numbers under 25,000 in base 10 which are palindromic in bases 2, 4 and 16:")
    var numbers []int
    for i := int64(0); i < 25000; i++ {
        b2 := strconv.FormatInt(i, 2)
        if b2 == reverse(b2) {
            b4 := strconv.FormatInt(i, 4)
            if b4 == reverse(b4) {
                b16 := strconv.FormatInt(i, 16)
                if b16 == reverse(b16) {
                    numbers = append(numbers, int(i))
                }
            }
        }
    }
    for i, n := range numbers {
        fmt.Printf("%6s ", rcu.Commatize(n))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n\nFound", len(numbers), "such numbers.")
}




Python: def reverse(n, base):
    r = 0
    while n > 0:
        r = r*base + n%base
        n = n//base
    return r
    
def palindrome(n, base):
    return n == reverse(n, base)
    
cnt = 0
for i in range(25000):
    if all(palindrome(i, base) for base in (2,4,16)):
        cnt += 1
        print("{:5}".format(i), end=" \n"[cnt % 12 == 0])

print()
Task: Long stairs




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    totalSecs := 0
    totalSteps := 0
    fmt.Println("Seconds    steps behind    steps ahead")
    fmt.Println("-------    ------------    -----------")
    for trial := 1; trial < 10000; trial++ {
        sbeh := 0
        slen := 100
        secs := 0
        for sbeh < slen {
            sbeh++
            for wiz := 1; wiz < 6; wiz++ {
                if rand.Intn(slen) < sbeh {
                    sbeh++
                }
                slen++
            }
            secs++
            if trial == 1 && secs > 599 && secs < 610 {
                fmt.Printf("%d        %d            %d\n", secs, sbeh, slen-sbeh)
            }
        }
        totalSecs += secs
        totalSteps += slen
    }
    fmt.Println("\nAverage secs taken:", float64(totalSecs)/10000)
    fmt.Println("Average final length of staircase:", float64(totalSteps)/10000)
}




Python: 

from numpy import mean
from random import sample

def gen_long_stairs(start_step, start_length, climber_steps, add_steps):
    secs, behind, total = 0, start_step, start_length
    while True:
        behind += climber_steps
        behind += sum([behind > n for n in sample(range(total), add_steps)])
        total += add_steps
        secs += 1
        yield (secs, behind, total)
        

ls = gen_long_stairs(1, 100, 1, 5)

print("Seconds  Behind  Ahead\n----------------------")
while True:
    secs, pos, len = next(ls)
    if 600 <= secs < 610:
        print(secs, "     ", pos, "   ", len - pos)
    elif secs == 610:
        break

print("\nTen thousand trials to top:")
times, heights = [], []
for trial in range(10_000):
    trialstairs = gen_long_stairs(1, 100, 1, 5)
    while True:
        sec, step, height = next(trialstairs)
        if step >= height:
            times.append(sec)
            heights.append(height)
            break

print("Mean time:", mean(times), "secs. Mean height:", mean(heights))
Task: Terminal control_Positional read




Go: package main


import "C"
import "fmt"

func main() {
    for i := 0; i < 80*25; i++ {
        fmt.Print("A")  
    }
    fmt.Println()
    conOut := C.GetStdHandle(C.STD_OUTPUT_HANDLE)
    info := C.CONSOLE_SCREEN_BUFFER_INFO{}
    pos := C.COORD{}
    C.GetConsoleScreenBufferInfo(conOut, &info)
    pos.X = info.srWindow.Left + 3 
    pos.Y = info.srWindow.Top + 6  
    var c C.wchar_t
    var le C.ulong
    ret := C.ReadConsoleOutputCharacterW(conOut, &c, 1, pos, &le)
    if ret == 0 || le <= 0 {
        fmt.Println("Something went wrong!")
        return
    }
    fmt.Printf("The character at column 3, row 6 is '%c'\n", c) 
}




Python: import curses
from random import randint



stdscr = curses.initscr()
for rows in range(10):
    line = ''.join([chr(randint(41, 90)) for i in range(10)])
    stdscr.addstr(line + '\n')


icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")


stdscr.move(irow, icol + 10)
stdscr.addstr('Character at column 3, row 6 = ' + ch + '\n')
stdscr.getch()

curses.endwin()
Task: Pseudo-random numbers_Middle-square method




Go: package main

import "fmt"

func random(seed int) int {
    return seed * seed / 1e3 % 1e6
}

func main() {
    seed := 675248
    for i := 1; i <= 5; i++ {
        seed = random(seed)
        fmt.Println(seed)
    }
}




Python: seed = 675248
def random():
    global seed
    seed = int(str(seed ** 2).zfill(12)[3:9])
    return seed
for _ in range(5):
    print(random())
Task: Image convolution




Go: package main

import (
    "fmt"
    "image"
    "image/color"
    "image/jpeg"
    "math"
    "os"
)



func kf3(k *[9]float64, src, dst *image.Gray) {
    for y := src.Rect.Min.Y; y < src.Rect.Max.Y; y++ {
        for x := src.Rect.Min.X; x < src.Rect.Max.X; x++ {
            var sum float64
            var i int
            for yo := y - 1; yo <= y+1; yo++ {
                for xo := x - 1; xo <= x+1; xo++ {
                    if (image.Point{xo, yo}).In(src.Rect) {
                        sum += k[i] * float64(src.At(xo, yo).(color.Gray).Y)
                    } else {
                        sum += k[i] * float64(src.At(x, y).(color.Gray).Y)
                    }
                    i++
                }
            }
            dst.SetGray(x, y,
                color.Gray{uint8(math.Min(255, math.Max(0, sum)))})
        }
    }
}

var blur = [9]float64{
    1. / 9, 1. / 9, 1. / 9,
    1. / 9, 1. / 9, 1. / 9,
    1. / 9, 1. / 9, 1. / 9}



func blurY(src *image.YCbCr) *image.YCbCr {
    dst := *src

    
    if src.Rect.Max.X == src.Rect.Min.X || src.Rect.Max.Y == src.Rect.Min.Y {
        return &dst
    }

    
    srcGray := image.Gray{src.Y, src.YStride, src.Rect}
    dstGray := srcGray
    dstGray.Pix = make([]uint8, len(src.Y))
    kf3(&blur, &srcGray, &dstGray) 

    
    dst.Y = dstGray.Pix                   
    dst.Cb = append([]uint8{}, src.Cb...) 
    dst.Cr = append([]uint8{}, src.Cr...)
    return &dst
}

func main() {
    
    
    f, err := os.Open("Lenna100.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    img, err := jpeg.Decode(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    f.Close()
    y, ok := img.(*image.YCbCr)
    if !ok {
        fmt.Println("expected color jpeg")
        return
    }
    f, err = os.Create("blur.jpg")
    if err != nil {
        fmt.Println(err)
        return
    }
    err = jpeg.Encode(f, blurY(y), &jpeg.Options{90})
    if err != nil {
        fmt.Println(err)
    }
}




Python: 
from PIL import Image, ImageFilter

if __name__=="__main__":
	im = Image.open("test.jpg")

	kernelValues = [-2,-1,0,-1,1,1,0,1,2] 
	kernel = ImageFilter.Kernel((3,3), kernelValues)

	im2 = im.filter(kernel)

	im2.show()
Task: Dice game probabilities




Go: package main

import(
    "math"
    "fmt"
)

func minOf(x, y uint) uint {
    if x < y {
        return x
    }
    return y
}

func throwDie(nSides, nDice, s uint, counts []uint) {
    if nDice == 0 {
        counts[s]++
        return
    }
    for i := uint(1); i <= nSides; i++ {
        throwDie(nSides, nDice - 1, s + i, counts)
    }
}

func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
    len1 := (nSides1 + 1) * nDice1
    c1 := make([]uint, len1)  
    throwDie(nSides1, nDice1, 0, c1)

    len2 := (nSides2 + 1) * nDice2
    c2 := make([]uint, len2)
    throwDie(nSides2, nDice2, 0, c2)
    p12 := math.Pow(float64(nSides1), float64(nDice1)) *
           math.Pow(float64(nSides2), float64(nDice2))

    tot := 0.0
    for i := uint(0); i < len1; i++ {
        for j := uint(0); j < minOf(i, len2); j++ {
            tot += float64(c1[i] * c2[j]) / p12
        }
    }
    return tot
}

func main() {
    fmt.Println(beatingProbability(4, 9, 6, 6))
    fmt.Println(beatingProbability(10, 5, 7, 6))
}




Python: from itertools import product

def gen_dict(n_faces, n_dice):
    counts = [0] * ((n_faces + 1) * n_dice)
    for t in product(range(1, n_faces + 1), repeat=n_dice):
        counts[sum(t)] += 1
    return counts, n_faces ** n_dice

def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
    c1, p1 = gen_dict(n_sides1, n_dice1)
    c2, p2 = gen_dict(n_sides2, n_dice2)
    p12 = float(p1 * p2)

    return sum(p[1] * q[1] / p12
               for p, q in product(enumerate(c1), enumerate(c2))
               if p[0] > q[0])

print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)
Task: Rosetta Code_Find unimplemented tasks




Go: package main

import (
    "encoding/xml"
    "fmt"
    "io"
    "net/http"
    "net/url"
)

const language = "Go"

var baseQuery = "http:
    "&format=xml&list=categorymembers&cmlimit=100"

func req(u string, foundCm func(string)) string {
    resp, err := http.Get(u)
    if err != nil {
        fmt.Println(err) 
        return ""
    }
    defer resp.Body.Close()
    for p := xml.NewDecoder(resp.Body); ; {
        t, err := p.RawToken()
        switch s, ok := t.(xml.StartElement); {
        case err == io.EOF:
            return ""
        case err != nil:
            fmt.Println(err)
            return ""
        case !ok:
            continue
        case s.Name.Local == "cm":
            for _, a := range s.Attr {
                if a.Name.Local == "title" {
                    foundCm(a.Value)
                }
            }
        case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
            s.Attr[0].Name.Local == "cmcontinue":
            return url.QueryEscape(s.Attr[0].Value)
        }
    }
    return ""
}

func main() {
    
    langMap := make(map[string]bool)
    storeLang := func(cm string) { langMap[cm] = true }
    languageQuery := baseQuery + "&cmtitle=Category:" + language
    continueAt := req(languageQuery, storeLang)
    for continueAt > "" {
        continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
    }

    
    if len(langMap) == 0 {
        fmt.Println("no tasks implemented for", language)
        return
    }

    
    printUnImp := func(cm string) {
        if !langMap[cm] {
            fmt.Println(cm)
        }
    }
    taskQuery := baseQuery + "&cmtitle=Category:Programming_Tasks"
    continueAt = req(taskQuery, printUnImp)
    for continueAt > "" {
        continueAt = req(taskQuery+"&cmcontinue="+continueAt, printUnImp)
    }
}




Python: 
from operator import attrgetter
from typing import Iterator

import mwclient

URL = 'www.rosettacode.org'
API_PATH = '/mw/'


def unimplemented_tasks(language: str,
                        *,
                        url: str,
                        api_path: str) -> Iterator[str]:
    
    site = mwclient.Site(url, path=api_path)
    all_tasks = site.categories['Programming Tasks']
    language_tasks = site.categories[language]
    name = attrgetter('name')
    all_tasks_names = map(name, all_tasks)
    language_tasks_names = set(map(name, language_tasks))
    for task in all_tasks_names:
        if task not in language_tasks_names:
            yield task


if __name__ == '__main__':
    tasks = unimplemented_tasks('Python', url=URL, api_path=API_PATH)
    print(*tasks, sep='\n')
Task: First-class functions_Use numbers analogously




Go: package main

import "fmt"

func main() {
    x := 2.
    xi := .5
    y := 4.
    yi := .25
    z := x + y
    zi := 1 / (x + y)
    

    numbers := []float64{x, y, z}
    inverses := []float64{xi, yi, zi}
    

    mfs := make([]func(float64) float64, len(numbers))
    for i := range mfs {
        mfs[i] = multiplier(numbers[i], inverses[i])
    }
    

    for _, mf := range mfs {
        fmt.Println(mf(1))
    }
}

func multiplier(n1, n2 float64) func(float64) float64 {
    
    n1n2 := n1 * n2
    
    return func(m float64) float64 {
        return n1n2 * m
    }
}




Python: IDLE 2.6.1      
>>> 
>>> x,xi, y,yi = 2.0,0.5, 4.0,0.25
>>> 
>>> z  = x + y
>>> zi = 1.0 / (x + y)
>>> 
>>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m)
>>> 
>>> numlist = [x, y, z]
>>> numlisti = [xi, yi, zi]
>>> 
>>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)]
[0.5, 0.5, 0.5]
>>>
Task: Almkvist-Giullera formula for pi




Go: package main

import (
    "fmt"
    "math/big"
    "strings"
)

func factorial(n int64) *big.Int {
    var z big.Int
    return z.MulRange(1, n)
}

var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)

func almkvistGiullera(n int64, print bool) *big.Rat {
    t1 := big.NewInt(32)
    t1.Mul(factorial(6*n), t1)
    t2 := big.NewInt(532*n*n + 126*n + 9)
    t3 := new(big.Int)
    t3.Exp(factorial(n), six, nil)
    t3.Mul(t3, three)
    ip := new(big.Int)
    ip.Mul(t1, t2)
    ip.Quo(ip, t3)
    pw := 6*n + 3
    t1.SetInt64(pw)
    tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
    if print {
        fmt.Printf("%d  %44d  %3d  %-35s\n", n, ip, -pw, tm.FloatString(33))
    }
    return tm
}

func main() {
    fmt.Println("N                               Integer Portion  Pow  Nth Term (33 dp)")
    fmt.Println(strings.Repeat("-", 89))
    for n := int64(0); n < 10; n++ {
        almkvistGiullera(n, true)
    }

    sum := new(big.Rat)
    prev := new(big.Rat)
    pow70 := new(big.Int).Exp(ten, seventy, nil)
    prec := new(big.Rat).SetFrac(one, pow70)
    n := int64(0)
    for {
        term := almkvistGiullera(n, false)
        sum.Add(sum, term)
        z := new(big.Rat).Sub(sum, prev)
        z.Abs(z)
        if z.Cmp(prec) < 0 {
            break
        }
        prev.Set(sum)
        n++
    }
    sum.Inv(sum)
    pi := new(big.Float).SetPrec(256).SetRat(sum)
    pi.Sqrt(pi)
    fmt.Println("\nPi to 70 decimal places is:")
    fmt.Println(pi.Text('f', 70))
}




Python: import mpmath as mp

with mp.workdps(72):

    def integer_term(n):
        p = 532 * n * n + 126 * n + 9
        return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)

    def exponent_term(n):
        return -(mp.mpf("6.0") * n + 3)

    def nthterm(n):
        return integer_term(n) * mp.mpf("10.0")**exponent_term(n)


    for n in range(10):
        print("Term ", n, '  ', int(integer_term(n)))


    def almkvist_guillera(floatprecision):
        summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
        for n in range(100000000):
            nextadd = summed + nthterm(n)
            if abs(nextadd - summed) < 10.0**(-floatprecision):
                break

            summed = nextadd

        return nextadd


    print('\nπ to 70 digits is ', end='')
    mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
    print('mpmath π is       ', end='')
    mp.nprint(mp.pi, 71)