WeixiangYan/CodeTransOcean huggingface dataset:
Task: Keyboard input_Obtain a Y or N response




Go: package main

import (
    "log"

    gc "code.google.com/p/goncurses"
)

func main() {
    s, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    var k gc.Key
    for {
        gc.FlushInput()
        s.MovePrint(20, 0, "Press y/n ")
        s.Refresh()
        switch k = s.GetChar(); k {
        default:
            continue
        case 'y', 'Y', 'n', 'N':
        }
        break
    }
    s.Printf("\nThanks for the %c!\n", k)
    s.Refresh()
    s.GetChar()
}




Python: 

try:
    from msvcrt import getch
except ImportError:
    def getch():
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

print "Press Y or N to continue"
while True:
    char = getch()
    if char.lower() in ("y", "n"):
        print char
        break
Task: Perfect numbers




Go: package main

import "fmt"

func computePerfect(n int64) bool {
    var sum int64
    for i := int64(1); i < n; i++ {
        if n%i == 0 {
            sum += i
        }
    }
    return sum == n
}



func isPerfect(n int64) bool {
    switch n {
    case 6, 28, 496, 8128, 33550336, 8589869056,
        137438691328, 2305843008139952128:
        return true
    }
    return false
}


func main() {
    for n := int64(1); ; n++ {
        if isPerfect(n) != computePerfect(n) {
            panic("bug")
        }
        if n%1e3 == 0 {
            fmt.Println("tested", n)
        }
    }
}




Python: def perf1(n):
    sum = 0
    for i in range(1, n):
        if n % i == 0:
            sum += i
    return sum == n
Task: Jacobsthal numbers




Go: package main

import (
    "fmt"
    "math/big"
)

func jacobsthal(n uint) *big.Int {
    t := big.NewInt(1)
    t.Lsh(t, n)
    s := big.NewInt(1)
    if n%2 != 0 {
        s.Neg(s)
    }
    t.Sub(t, s)
    return t.Div(t, big.NewInt(3))
}

func jacobsthalLucas(n uint) *big.Int {
    t := big.NewInt(1)
    t.Lsh(t, n)
    a := big.NewInt(1)
    if n%2 != 0 {
        a.Neg(a)
    }
    return t.Add(t, a)
}

func main() {
    jac := make([]*big.Int, 30)
    fmt.Println("First 30 Jacobsthal numbers:")
    for i := uint(0); i < 30; i++ {
        jac[i] = jacobsthal(i)
        fmt.Printf("%9d ", jac[i])
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:")
    for i := uint(0); i < 30; i++ {
        fmt.Printf("%9d ", jacobsthalLucas(i))
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 20 Jacobsthal oblong numbers:")
    for i := uint(0); i < 20; i++ {
        t := big.NewInt(0)
        fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1]))
        if (i+1)%5 == 0 {
            fmt.Println()
        }
    }

    fmt.Println("\nFirst 20 Jacobsthal primes:")
    for n, count := uint(0), 0; count < 20; n++ {
        j := jacobsthal(n)
        if j.ProbablyPrime(10) {
            fmt.Println(j)
            count++
        }
    }
}




Python: 
from math import floor, pow

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

def odd(n):
    return n and 1 != 0
    
def jacobsthal(n):
    return floor((pow(2,n)+odd(n))/3)

def jacobsthal_lucas(n):
    return int(pow(2,n)+pow(-1,n))

def jacobsthal_oblong(n):
    return jacobsthal(n)*jacobsthal(n+1)


if __name__ == '__main__':
    print("First 30 Jacobsthal numbers:")
    for j in range(0, 30):
        print(jacobsthal(j), end="  ")

    print("\n\nFirst 30 Jacobsthal-Lucas numbers: ")
    for j in range(0, 30):
        print(jacobsthal_lucas(j), end = '\t')

    print("\n\nFirst 20 Jacobsthal oblong numbers: ")
    for j in range(0, 20):
        print(jacobsthal_oblong(j), end="  ")

    print("\n\nFirst 10 Jacobsthal primes: ")
    for j in range(3, 33):
        if isPrime(jacobsthal(j)):
            print(jacobsthal(j))
Task: Sorting algorithms_Bead sort




Go: package main

import (
    "fmt"
    "sync"
)

var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000

const bead = 'o'

func main() {
    fmt.Println("before:", a)
    beadSort()
    fmt.Println("after: ", a)
}

func beadSort() {
    
    all := make([]byte, aMax*len(a))
    
    
    abacus := make([][]byte, aMax)
    for pole, space := 0, all; pole < aMax; pole++ {
        abacus[pole] = space[:len(a)]
        space = space[len(a):]
    }
    
    var wg sync.WaitGroup
    
    
    
    wg.Add(len(a))
    for row, n := range a {
        go func(row, n int) {
            for pole := 0; pole < n; pole++ {
                abacus[pole][row] = bead
            }
            wg.Done()
        }(row, n)
    }
    wg.Wait()
    
    wg.Add(aMax)
    for _, pole := range abacus {
        go func(pole []byte) {
            
            top := 0
            for row, space := range pole {
                if space == bead {
                    
                    
                    
                    
                    
                    pole[row] = 0
                    pole[top] = bead
                    top++
                }
            }
            wg.Done()
        }(pole)
    }
    wg.Wait()
    
    for row := range a {
        x := 0
        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
            x++
        }
        a[len(a)-1-row] = x
    }
}




Python: 
from itertools import zip_longest


def beadsort(l):
    return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))



print(beadsort([5,3,1,7,4,1,1]))
Task: Arbitrary-precision integers (included)




Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	x := big.NewInt(2)
	x = x.Exp(big.NewInt(3), x, nil)
	x = x.Exp(big.NewInt(4), x, nil)
	x = x.Exp(big.NewInt(5), x, nil)
	str := x.String()
	fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
		len(str),
		str[:20],
		str[len(str)-20:],
	)
}




Python: >>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Task: Draw a sphere




Go: package main

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

type vector [3]float64

func normalize(v *vector) {
    invLen := 1 / math.Sqrt(dot(v, v))
    v[0] *= invLen
    v[1] *= invLen
    v[2] *= invLen
}

func dot(x, y *vector) float64 {
    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}

func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
    w, h := r*4, r*3
    img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
    vec := new(vector)
    for x := -r; x < r; x++ {
        for y := -r; y < r; y++ {
            if z := r*r - x*x - y*y; z >= 0 {
                vec[0] = float64(x)
                vec[1] = float64(y)
                vec[2] = math.Sqrt(float64(z))
                normalize(vec)
                s := dot(dir, vec)
                if s < 0 {
                    s = 0
                }
                lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
                if lum < 0 {
                    lum = 0
                } else if lum > 255 {
                    lum = 255
                }
                img.SetGray(x, y, color.Gray{uint8(lum)})
            }
        }
    }
    return img
}

func main() {
    dir := &vector{-30, -30, 50}
    normalize(dir)
    img := drawSphere(200, 1.5, .2, dir)
    f, err := os.Create("sphere.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, img); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}




Python: import math

shades = ('.',':','!','*','o','e','&','

def normalize(v):
	len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
	return (v[0]/len, v[1]/len, v[2]/len)

def dot(x,y):
	d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
	return -d if d < 0 else 0

def draw_sphere(r, k, ambient, light):
	for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
		x = i + 0.5
		line = ''

		for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
			y = j/2 + 0.5
			if x*x + y*y <= r*r:
				vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
				b = dot(light,vec)**k + ambient
				intensity = int((1-b)*(len(shades)-1))
				line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
			else:
				line += ' '

		print(line)

light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)
Task: Least common multiple




Go: package main

import (
    "fmt"
    "math/big"
)

var m, n, z big.Int

func init() {
    m.SetString("2562047788015215500854906332309589561", 10)
    n.SetString("6795454494268282920431565661684282819", 10)
}

func main() {
    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}




Python: >>> import fractions
>>> def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0

>>> lcm(12, 18)
36
>>> lcm(-6, 14)
42
>>> assert lcm(0, 2) == lcm(2, 0) == 0
>>>
Task: Loops_Break




Go: package main

import "fmt"
import "math/rand"
import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    for {
        a := rand.Intn(20)
        fmt.Println(a)
        if a == 10 {
            break
        }
        b := rand.Intn(20)
        fmt.Println(b)
    }
}




Python: from random import randrange

while True:
    a = randrange(20)
    print(a)
    if a == 10:
        break
    b = randrange(20)
    print(b)
Task: Hello world_Line printer




Go: package main

import (
	"fmt"
	"os"
)

func main() {
	lp0, err := os.Create("/dev/lp0")

	if err != nil {
		panic(err)
	}

	defer lp0.Close()

	fmt.Fprintln(lp0, "Hello World!")
}




Python: lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()
Task: Water collected between towers




Go: package main

import "fmt"

func maxl(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := 0; i < len(hm);i++{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func maxr(hm []int ) []int{
	res := make([]int,len(hm))
	max := 1
	for i := len(hm) - 1 ; i >= 0;i--{
		if(hm[i] > max){
			max = hm[i]
		}
		res[i] = max;
	}
	return res
}
func min(a,b []int)  []int {
	res := make([]int,len(a))
	for i := 0; i < len(a);i++{
		if a[i] >= b[i]{
			res[i] = b[i]
		}else {
			res[i] = a[i]
		}
	}
	return res
}
func diff(hm, min []int) []int {
	res := make([]int,len(hm))
	for i := 0; i < len(hm);i++{
		if min[i] > hm[i]{
			res[i] = min[i] - hm[i]
		}
	}
	return res
}
func sum(a []int) int {
	res := 0
	for i := 0; i < len(a);i++{
		res += a[i]
	}
	return res
}

func waterCollected(hm []int) int {
	maxr := maxr(hm)
	maxl := maxl(hm)
	min := min(maxr,maxl)
	diff := diff(hm,min)
	sum := sum(diff)
	return sum
}


func main() {
	fmt.Println(waterCollected([]int{1, 5, 3, 7, 2}))
	fmt.Println(waterCollected([]int{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}))
	fmt.Println(waterCollected([]int{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}))
	fmt.Println(waterCollected([]int{5, 5, 5, 5}))
	fmt.Println(waterCollected([]int{5, 6, 7, 8}))
	fmt.Println(waterCollected([]int{8, 7, 7, 6}))
	fmt.Println(waterCollected([]int{6, 7, 10, 7, 6}))
}




Python: def water_collected(tower):
    N = len(tower)
    highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
    highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
    water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
        for n in range(N)]
    print("highest_left:  ", highest_left)
    print("highest_right: ", highest_right)
    print("water_level:   ", water_level)
    print("tower_level:   ", tower)
    print("total_water:   ", sum(water_level))
    print("")
    return sum(water_level)

towers = [[1, 5, 3, 7, 2],
    [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
    [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
    [5, 5, 5, 5],
    [5, 6, 7, 8],
    [8, 7, 7, 6],
    [6, 7, 10, 7, 6]]

[water_collected(tower) for tower in towers]
Task: Descending primes




Go: package main

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

func combinations(a []int, k int) [][]int {
    n := len(a)
    c := make([]int, k)
    var combs [][]int
    var combine func(start, end, index int)
    combine = func(start, end, index int) {
        if index == k {
            t := make([]int, len(c))
            copy(t, c)
            combs = append(combs, t)
            return
        }
        for i := start; i <= end && end-i+1 >= k-index; i++ {
            c[index] = a[i]
            combine(i+1, end, index+1)
        }
    }
    combine(0, n-1, 0)
    return combs
}

func powerset(a []int) (res [][]int) {
    if len(a) == 0 {
        return
    }
    for i := 1; i <= len(a); i++ {
        res = append(res, combinations(a, i)...)
    }
    return
}

func main() {
    ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
    var descPrimes []int
    for i := 1; i < len(ps); i++ {
        s := ""
        for _, e := range ps[i] {
            s += string(e + '0')
        }
        p, _ := strconv.Atoi(s)
        if rcu.IsPrime(p) {
            descPrimes = append(descPrimes, p)
        }
    }
    sort.Ints(descPrimes)
    fmt.Println("There are", len(descPrimes), "descending primes, namely:")
    for i := 0; i < len(descPrimes); i++ {
        fmt.Printf("%8d ", descPrimes[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
}




Python: from sympy import isprime

def descending(xs=range(10)):
    for x in xs:
        yield x
        yield from descending(x*10 + d for d in range(x%10))

for i, p in enumerate(sorted(filter(isprime, descending()))):
    print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')

print()
Task: Square-free integers




Go: package main

import (
    "fmt"
    "math"
)

func sieve(limit uint64) []uint64 {
    primes := []uint64{2}
    c := make([]bool, limit+1) 
    
    p := uint64(3)
    for {
        p2 := p * p
        if p2 > limit {
            break
        }
        for i := p2; i <= limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    for i := uint64(3); i <= limit; i += 2 {
        if !c[i] {
            primes = append(primes, i)
        }
    }
    return primes
}

func squareFree(from, to uint64) (results []uint64) {
    limit := uint64(math.Sqrt(float64(to)))
    primes := sieve(limit)
outer:
    for i := from; i <= to; i++ {
        for _, p := range primes {
            p2 := p * p
            if p2 > i {
                break
            }
            if i%p2 == 0 {
                continue outer
            }
        }
        results = append(results, i)
    }
    return
}

const trillion uint64 = 1000000000000

func main() {
    fmt.Println("Square-free integers from 1 to 145:")
    sf := squareFree(1, 145)
    for i := 0; i < len(sf); i++ {
        if i > 0 && i%20 == 0 {
            fmt.Println()
        }
        fmt.Printf("%4d", sf[i])
    }

    fmt.Printf("\n\nSquare-free integers from %d to %d:\n", trillion, trillion+145)
    sf = squareFree(trillion, trillion+145)
    for i := 0; i < len(sf); i++ {
        if i > 0 && i%5 == 0 {
            fmt.Println()
        }
        fmt.Printf("%14d", sf[i])
    }

    fmt.Println("\n\nNumber of square-free integers:\n")
    a := [...]uint64{100, 1000, 10000, 100000, 1000000}
    for _, n := range a {
        fmt.Printf("  from %d to %d = %d\n", 1, n, len(squareFree(1, n)))
    }
}




Python: import math

def SquareFree ( _number ) :
	max = (int) (math.sqrt ( _number ))

	for root in range ( 2, max+1 ):					
		if 0 == _number % ( root * root ):
			return False

	return True

def ListSquareFrees( _start, _end ):
	count = 0
	for i in range ( _start, _end+1 ):
		if True == SquareFree( i ):
			print ( "{}\t".format(i), end="" )
			count += 1

	print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))

ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
Task: Jaro similarity




Go: package main

import "fmt"

func jaro(str1, str2 string) float64 {
    if len(str1) == 0 && len(str2) == 0 {
        return 1
    }
    if len(str1) == 0 || len(str2) == 0 {
        return 0
    }
    match_distance := len(str1)
    if len(str2) > match_distance {
        match_distance = len(str2)
    }
    match_distance = match_distance/2 - 1
    str1_matches := make([]bool, len(str1))
    str2_matches := make([]bool, len(str2))
    matches := 0.
    transpositions := 0.
    for i := range str1 {
        start := i - match_distance
        if start < 0 {
            start = 0
        }
        end := i + match_distance + 1
        if end > len(str2) {
            end = len(str2)
        }
        for k := start; k < end; k++ {
            if str2_matches[k] {
                continue
            }
            if str1[i] != str2[k] {
                continue
            }
            str1_matches[i] = true
            str2_matches[k] = true
            matches++
            break
        }
    }
    if matches == 0 {
        return 0
    }
    k := 0
    for i := range str1 {
        if !str1_matches[i] {
            continue
        }
        for !str2_matches[k] {
            k++
        }
        if str1[i] != str2[k] {
            transpositions++
        }
        k++
    }
    transpositions /= 2
    return (matches/float64(len(str1)) +
        matches/float64(len(str2)) +
        (matches-transpositions)/matches) / 3
}

func main() {
    fmt.Printf("%f\n", jaro("MARTHA", "MARHTA"))
    fmt.Printf("%f\n", jaro("DIXON", "DICKSONX"))
    fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH"))
}




Python: 

from __future__ import division


def jaro(s, t):
    
    s_len = len(s)
    t_len = len(t)

    if s_len == 0 and t_len == 0:
        return 1

    match_distance = (max(s_len, t_len) // 2) - 1

    s_matches = [False] * s_len
    t_matches = [False] * t_len

    matches = 0
    transpositions = 0

    for i in range(s_len):
        start = max(0, i - match_distance)
        end = min(i + match_distance + 1, t_len)

        for j in range(start, end):
            if t_matches[j]:
                continue
            if s[i] != t[j]:
                continue
            s_matches[i] = True
            t_matches[j] = True
            matches += 1
            break

    if matches == 0:
        return 0

    k = 0
    for i in range(s_len):
        if not s_matches[i]:
            continue
        while not t_matches[k]:
            k += 1
        if s[i] != t[k]:
            transpositions += 1
        k += 1

    return ((matches / s_len) +
            (matches / t_len) +
            ((matches - transpositions / 2) / matches)) / 3


def main():
    

    for s, t in [('MARTHA', 'MARHTA'),
                 ('DIXON', 'DICKSONX'),
                 ('JELLYFISH', 'SMELLYFISH')]:
        print("jaro(%r, %r) = %.10f" % (s, t, jaro(s, t)))


if __name__ == '__main__':
    main()
Task: Sum and product puzzle




Go: package main

import "fmt"

type pair struct{ x, y int }

func main() {
	
	
	
	const max = 1685
	var all []pair
	for a := 2; a < max; a++ {
		for b := a + 1; b < max-a; b++ {
			all = append(all, pair{a, b})
		}
	}
	fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)")
	products := countProducts(all)

	
	
	var sPairs []pair
pairs:
	for _, p := range all {
		s := p.x + p.y
		
		for a := 2; a < s/2+s&1; a++ {
			b := s - a
			if products[a*b] == 1 {
				
				continue pairs
			}
		}
		sPairs = append(sPairs, p)
	}
	fmt.Println("S starts with", len(sPairs), "possible pairs.")
	
	sProducts := countProducts(sPairs)

	
	
	var pPairs []pair
	for _, p := range sPairs {
		if sProducts[p.x*p.y] == 1 {
			pPairs = append(pPairs, p)
		}
	}
	fmt.Println("P then has", len(pPairs), "possible pairs.")
	
	pSums := countSums(pPairs)

	
	var final []pair
	for _, p := range pPairs {
		if pSums[p.x+p.y] == 1 {
			final = append(final, p)
		}
	}

	
	switch len(final) {
	case 1:
		fmt.Println("Answer:", final[0].x, "and", final[0].y)
	case 0:
		fmt.Println("No possible answer.")
	default:
		fmt.Println(len(final), "possible answers:", final)
	}
}

func countProducts(list []pair) map[int]int {
	m := make(map[int]int)
	for _, p := range list {
		m[p.x*p.y]++
	}
	return m
}

func countSums(list []pair) map[int]int {
	m := make(map[int]int)
	for _, p := range list {
		m[p.x+p.y]++
	}
	return m
}


func decomposeSum(s int) []pair {
	pairs := make([]pair, 0, s/2)
	for a := 2; a < s/2+s&1; a++ {
		pairs = append(pairs, pair{a, s - a})
	}
	return pairs
}




Python: 

from collections import Counter

def decompose_sum(s):
    return [(a,s-a) for a in range(2,int(s/2+1))]


all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)


product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_pairs = [(a,b) for a,b in all_pairs if
    all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]


product_counts = Counter(c*d for c,d in s_pairs)
p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]


sum_counts = Counter(c+d for c,d in p_pairs)
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]

print(final_pairs)
Task: Fairshare between two and more




Go: package main

import (
    "fmt"
    "sort"
    "strconv"
    "strings"
)

func fairshare(n, base int) []int {
    res := make([]int, n)
    for i := 0; i < n; i++ {
        j := i
        sum := 0
        for j > 0 {
            sum += j % base
            j /= base
        }
        res[i] = sum % base
    }
    return res
}

func turns(n int, fss []int) string {
    m := make(map[int]int)
    for _, fs := range fss {
        m[fs]++
    }
    m2 := make(map[int]int)
    for _, v := range m {
        m2[v]++
    }
    res := []int{}
    sum := 0
    for k, v := range m2 {
        sum += v
        res = append(res, k)
    }
    if sum != n {
        return fmt.Sprintf("only %d have a turn", sum)
    }
    sort.Ints(res)
    res2 := make([]string, len(res))
    for i := range res {
        res2[i] = strconv.Itoa(res[i])
    }
    return strings.Join(res2, " or ")
}

func main() {
    for _, base := range []int{2, 3, 5, 11} {
        fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
    }
    fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
    for _, base := range []int{191, 1377, 49999, 50000, 50001} {
        t := turns(base, fairshare(50000, base))
        fmt.Printf("  With %d people: %s\n", base, t)
    }
}




Python: from itertools import count, islice

def _basechange_int(num, b):
    
    if num == 0:
        return [0]
    result = []
    while num != 0:
        num, d = divmod(num, b)
        result.append(d)
    return result[::-1]

def fairshare(b=2):
    for i in count():
        yield sum(_basechange_int(i, b)) % b

if __name__ == '__main__':
    for b in (2, 3, 5, 11):
        print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}")