0% found this document useful (0 votes)
166 views

Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet

The document compares programming idioms across multiple languages: 1. It shows how to print "Hello World" in Go, Rust, Python, Kotlin, Scala, and Dart. 2. It demonstrates looping to print "Hello" 10 times in each language. 3. It provides an example of defining a procedure called "finish" that prints a message without returning a value in each language. 4. It gives the definition of a function called "square" that returns the square of a number in each language.

Uploaded by

Cem Sourtimes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views

Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet

The document compares programming idioms across multiple languages: 1. It shows how to print "Hello World" in Go, Rust, Python, Kotlin, Scala, and Dart. 2. It demonstrates looping to print "Hello" 10 times in each language. 3. It provides an example of defining a procedure called "finish" that prints a message without returning a value in each language. 4. It gives the definition of a function called "square" that returns the square of a number in each language.

Uploaded by

Cem Sourtimes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

Programming-Idioms.org The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0


Go
Rust
Python
Kotlin
Scala
Dart
1 Print Hello World import "fmt" println!("Hello World"); print("Hello World") println("Hello wo println("Hello, Worl print("Hello Worl
Print a literal string on standard output rld!") d!") d");
fmt.Println("Hello World")
Alternative implementation:

Alternative implementation: print('Hello World')

package main

Alternative implementation:
func main(){print("Hello World")}
import __hello__

2 Print Hello 10 times import "fmt" for _ in 0..10 { println! for _ in range(10):
(0..9).forEach {
(0 until 10).foreach( print("Hello\n" *
Loop to execute some code a constant number ("Hello"); } print("Hello") println("Hell _ => println("Hell 10);

of times for i := 0; i < 10; i++ {

0..10 syntax creates range Indentation is mandatory o")


o")) This will print 'Hello' in
fmt.Println("Hello")

iterator.
}
a new line 10 times
}

Alternative implementation: 0..9 is inclusive Alternative


The compiler doesn't report print("Hello\n"*10) implementation:
Alternative implementation:
unused variables prefixed with Alternative println("Hello\n"*10)
import "fmt"
Sequence repetition is
an underscore. implementation:
import "strings" performed.
repeat(10) {

fmt.Println(strings.Repeat("Hello\n", 10)) Alternative implementation: Alternative implementation: println("Hell


print!("{}", "Hello\n".repe >>>print(10/0) o")

at(10)); }

Alternative
implementation:
for(x in 1..10) {

println("Hel
lo")

3 Create a procedure import "fmt" fn finish(name : &str) {


def finish(name):
fun finish(name: def doSomething(name: void finish(String
Like a function which doesn't return any value, println!("My job here i print(f'My job here i String) {
String): Unit = {
name) {

thus has only side effects (e.g. Print to standard func finish(name string) {

s done. Goodbye {}", name);


s done. Goodbye {name}') println("My job println(s"My job he print("My job he
output) fmt.Println("My job here is done. Good by
} Variable name inside curly here is done. Goo re is done. Goodbye re is done. Goodby
e " + name)

The actual return type is Unit, braces will be replaced by its dbye $name")
${name}")
e $name.");

}
typed '()' and can be omitted value. This is called "f-strings" } } }
There is no return type in the signature, before the
from function signature. introduced in Python version
{.
3.6
Alternative implementation:
import "fmt"

finish := func(name string) {

fmt.Println("My job here is done. G


ood bye " + name)

This is a closure.

finish is a variable of type func(string).



Go
Rust
Python
Kotlin
Scala
Dart
4 Create a function func square(x int) int {
fn square(x : u32) -> u32 { def square(x):
fun square(x: In def square(x:Int): In int square(int x)
Create a function which returns the square of an return x*x
x * x } return x*x t) = x * x t = x*x => x * x;
integer } Last expression in block is used You don't have to explicitly
The return type is after the parameter list as a return value. write the return type

Alternative implementation:
def square(x):

return x**2

You can use power operator


5 Create a 2D Point data structure type Point struct {
struct Point {
from dataclasses import d data class Point case class Point(x: F class Point {

Declare a container type for two floating-point x, y float64


x: f64,
ataclass (val x: Float, va loat, y: Float) double x, y;

numbers x and y } y: f64,


l y: Float) }
@dataclass

}
class Point:

Alternative
x: float

Alternative implementation: implementation:


y: float
struct Point(f64, f64); class Point {

Alternative implementation: double x, y;

Point(this.x, th
from collections import n
is.y);

amedtuple
}
Point = namedtuple("Poin
With constructor,
t", "x y")
which you will almost
always have.
6 Iterate over list values for _, x := range items {
for x in items {
for x in items:
items.forEach { d items.foreach{doSomet items.forEach(doSo
Do something with each item x of an array-like doSomething(x)
do_something(x);
doSomething( x ) oSomething(it) } hing(_)} mething);
collection items, regardless indexes. } }
You have to explicitly ignore the index loop Alternative Alternative
variable, with the blank identifier _ Alternative implementation: implementation: implementation:
items.into_iter().for_each items.forEach(::d items.foreach(doSomet
(|x| do_something(x)); oSomething) hing)
Using a function when the method you're
reference. calling on each item in
the collection only takes a
Alternative single parameter, you can
implementation: omit specifying it.
for (x in items)
doSomething(x) Alternative
implementation:
for {

x <- items

} doSomething(x)

Go
Rust
Python
Kotlin
Scala
Dart
7 Iterate over list indexes and values import "fmt" for (i, x) in items.iter(). for i, x in enumerate(ite items.forEachInde val items = List("a", for (var i = 0; i
Print each index i with its value x from an array- enumerate() {
ms):
xed { i, x ->
"b", "c")
< items.length; i+
like collection items for i, x := range items {

println!("Item {} = print i, x println("i=$i x items.zipWithIndex.fo +) {

fmt.Printf("Item %d = %v \n", i, x)

{}", i, x);
=$x")
reach{ case (item, in print('index=$i,
}
} } dex) =>
value=${items
The range clause gives you index i and value x at println(s"$index => [i]}');

the same time as loop variables Alternative implementation: $item")


}
items.iter().enumerate().fo }

r_each(|(i, x)| {
zipWithIndex takes each Alternative
println!("Item {} = item in a collection and implementation:
{}", i, x);
replaces it with a tuple of items.asMap().forE
}) (item, index) ach((i, value) {

print('index=$i,
value=$value');

});

An alternative, but not


really idiomatic.
8 Initialize a new map (associative array) x := map[string]int {"one": 1, "two": 2} use std::collections::BTree x = {"one" : 1, "two" : val x = mapOf("on val x = Map("a" -> 1, var x = {

Create a new map object x, and provide some Map; 2} e" to 1, "two" to "b" -> 2, "c" -> 3) "one": 1,

(key, value) pairs as initial content. 2)


"two": 2

let mut x = BTreeMap::new


Only if performance };
();

x.insert("one", 1);
isn't critical. See the
x.insert("two", 2); docs.

Something different than a Alternative


BTreeMap might be used, implementation:
depending on the usage.

val x = mutableMa
pOf<String, Int>
The function new of the type
().apply {

BTreeMap returns a usable


this["one"] =
map.

The map is stored mutable in the


this["two"] =
variable x.

}
Maps in Rust are generic and
type safe at compile time.
Alternative
Alternative implementation: implementation:
use std::collections::HashM val x = mutableMa
ap; pOf<String, Int>
()

let x: HashMap<&str, i32> =


x["one"] = 1

x["two"] = 2
("one", 1),

("two", 2),

].into_iter().collect();

Go
Rust
Python
Kotlin
Scala
Dart
9 Create a Binary Tree data structure type BinTree struct {
struct BinTree<T> {
class Node:
data class Node(
class Node<T> {

The structure must be recursive because left Value valueType


value: T,
def __init__(sel     val key: Int,
final T value;

child and right child are binary trees too. A node Left *BinTree
left: Option<Box<BinTre f, data):
    val left: Nod Node<T> left, ri
has access to children nodes, but not to its Right *BinTree
e<T>>>,
self.data e? = null,
ght;

parent. }
right: Option<Box<BinTr = data
    val right: No Node(this.value,
ee<T>>>,
self.left de? = null
{this.left, this.r
} = None
) ight});

self.righ }
t = None

Alternative implementation:
class Node:

def __init__(self, dat


a, left_child, right_chil
d):

self.data = data

self._left_child = le
ft_child

self._right_child = r
ight_child

Go
Rust
Python
Kotlin
Scala
Dart
10 Shuffle a list import "math/rand" extern crate rand;
from random import shuffl mutableList.shuff import scala.util.Ran x.shuffle();
Generate a random permutation of the elements use rand::{Rng, StdRng}; e le() dom
for i := range x {
This alters the content
of list x
j := rand.Intn(i + 1)
let mut rng = StdRng::new shuffle(x) Only mutable lists val items = List(1, of x.
x[i], x[j] = x[j], x[i]
().unwrap();
can be shuffled in- 2, 3, 4, 5)

This alters the list Alternative


} rng.shuffle(&mut x); place. val shuffledItems = R
implementation:
This alters the slice content.
Requires the rand crate Alternative implementation: andom.shuffle(items)
Alternative var shuffled = x.t
This requires no extra allocation. (https://crates.io/crates/rand) import random
implementation: oList()..shuffle
Alternative implementation: Alternative implementation: random.shuffle(list) val newList = lis ();
t.shuffled()
import "math/rand" use rand::seq::SliceRandom;
random.shuffle is a inbuilt This keeps x
use rand::thread_rng; function that will shuffle the Immutable lists unchanged.
y := make([]T, len(x))
data. cannot be shuffled
perm := rand.Perm(len(x))
let mut rng = thread_rng();

in-place.
for i, v := range perm {
x.shuffle(&mut rng);
y[v] = x[i]
Requires the rand crate.

} (https://crates.io/crates/rand)
This allocates a temporary slice of int, and a new
destination slice y of type T.

x is left unchanged.

Alternative implementation:
import "math/rand"

rand.Shuffle(len(x), func(i, j int) {

x[i], x[j] = x[j], x[i]

})
Last argument is a swap func.

This works in Go ≥ 1.10

Alternative implementation:
import "math/rand"

for i := len(x) - 1; i > 0; i-- {

j := rand.Intn(i + 1)

x[i], x[j] = x[j], x[i]

}

Go
Rust
Python
Kotlin
Scala
Dart
11 Pick a random element from a list import "math/rand" use rand::{self, Rng}; import random list.random() import scala.util.Ran x[new Random().nex
List x must be non-empty. dom tInt(x.length)];
x[rand.Intn(len(x))] x[rand::thread_rng().gen_ra random.choice(x)
nge(0..x.len())] val x = List(1, 2, 3,
Alternative implementation: gen_range returns a number 4)

import "math/rand" between 0 (inclusive) and x.len() x.apply(Random.nextIn


(exclusive) t(x.size))
func pickT(x []T) T {

apply can be called


return x[rand.Intn(len(x))]
Alternative implementation: without the name or dot

}
use rand::seq::SliceRandom; x(Random.nextInt(x.size))
If you decide to implement pickT, you will have to
write it separately for each desired type T. let mut rng = rand::thread_
rng();

let choice = x.choose(&mut


rng).unwrap();

The choose method returns an


Option which is None if x is
empty.
12 Check if list contains a value func Contains(list []T, x T) bool {
list.contains(&x); x in list x in list list.contains(x)
list.contains(x);
Check if list contains a value x.
for _, item := range list {
See also more general This indirectly calls
list is an iterable finite container. if item == x {
Alternative
alternative implementations. list._contains__() and returns
return true
True or False implementation:
}
Alternative implementation: list.contains(x)
}
list.iter().any(|v| v == &
return false
x)
}
This works for most iterable
This func must be written for each type T of your types.
needs (with a different name each).

Alternative implementation:
You may use any type T compatible with operator (&list).into_iter().any(|v|
== v == &x)
This is the the truly general
version, but it isn't the most
idiomatic.
13 Iterate over map keys and values import "fmt" use std::collections::BTree for k, v in mymap.items mymap.entries.for val x = Map("a" -> 1, mymap.forEach((k,
Access each key k with its value x from an Map; ():
Each { print("${i "b" -> 2, "c" -> 3)
v) => print('Key=
associative array mymap, and print them. for k, x := range mymap {

print(k, v) t.key} ${it.valu x.foreach{ case (key, $k, Value=$v'));


fmt.Println("Key =", k, ", Value =", x)
for (k, x) in &mymap {

e}") } value) => println


} println!("Key={key}, Va
(s"$key => $value")}
Do not rely on the order of the traversal ! The order lue={val}", key=k, val=x);
Alternative
is undefined and is intentionaly randomized by the }
implementation: Alternative
Go runtime. You can also print collections in implementation:
mymap.forEach {
a 'nice' way with `println!("{:?}",
k, v -> println mymap.foreach { case
mymap);` which is the Debug-
("$k -> $v") } (k, x) => println
representation. You can also use
(s"$k => $x") }
"{:#?}" for the pretty version.

This example works the same if


you replace BTreeMap with
HashMap.

Go
Rust
Python
Kotlin
Scala
Dart
14 Pick uniformly a random floating point import "math/rand" extern crate rand;
import random import kotlin.ran import math.random import 'dart:mat
number in [a..b) use rand::{Rng, thread_rn dom.Random h';
Pick a random number greater than or equals to func pick(a, b float64) float64 {
random.uniform(a,b) def randomDraw(min: D
g};
a, strictly inferior to b. Precondition : a < b. return a + (rand.Float64() * (b-a))
The end-point value b may or Random.nextDouble ouble, max: Double): double pick(num a,
} thread_rng().gen_range(a.. may not be included in the (a,b) Double = {
num b) => a + new
b); range depending on floating- val range = max - m Random().nextDoubl
If you need to generate a lot of point rounding in
e() * (b - a);

random stuff, save the (random.doubleValue


thread_rng as a variable so it is * range) + min

only initialized once. }

15 Pick uniformly a random integer in [a..b] import "math/rand" extern crate rand;
import random fun pick(a: Int, import util.Random import 'dart:mat
Pick a random integer greater than or equals to use rand::distributions::{I b: Int): Int {
h';
a, inferior or equals to b. Precondition : a < b. func pick(a,b int) int {
random.randint(a,b) a + Random.nextInt(b
ndependentSample, Range}; return (a..
return a + rand.Intn(b-a+1)
Upper bound b is included. + 1) int pick(int a, in
b).random()

} fn pick(a: i32, b: i32) -> t b) => a + new Ra


}
(b-a+1) is needed to have upper bound b included. i32 {
ndom().nextInt(b -
let between = Range::ne a + 1);
w(a, b);

let mut rng = rand::thr


ead_rng();

between.ind_sample(&mut
rng)

Alternative implementation:
use rand::distributions::Di
stribution;

use rand::distributions::Un
iform;

Uniform::new_inclusive(a,
b).sample(&mut rand::thread
_rng())

16 Depth-first traversing of a binary tree func (bt *BinTree) Dfs(f func(*BinTree)) {


def dfs(bt):
traverse(Node bt,
Call a function f on every node of binary tree bt, if bt == nil {
if bt is None:
f(value)) {

in depth-first infix order return


return
if (bt == null)
}
dfs(bt.left)
return;

bt.Left.Dfs(f)
f(bt)
traverse(bt.lef
f(bt)
dfs(bt.right) t, f);

bt.Right.Dfs(f)
Recursive DFS. f(bt.value);

} traverse(bt.rig
The function f is a parameter of the traversal ht, f);

method Dfs. }

It's legit to call a method on a nil receiver, and


useful to make code more concise with less checks
for nil.

Go
Rust
Python
Kotlin
Scala
Dart
17 Create a Tree data structure type Tree struct {
struct Node<T> {
class Node:
case class Node[T](va class Node<T> {

The structure must be recursive. A node may Key keyType


value: T,
def __init__(self, va lue: T, children: Lis final T value;

have zero or more children. A node has access Deco valueType


children: Vec<Node<T>>,
lue, *children):
t[Node[T]] = Nil) final List<Node<
to its children nodes, but not to its parent. Children []*Tree
} self.value = valu T>> children;

}
e
Node(this.value,
keyType should be easily comparable.
self.children = l this.children);

valueType is a type of value associated with ist(children) }

current node.

Children is a slice of pointers.

Note that in Go you can call methods of pointer


type *Tree even on a nil receiver (an empty tree).
18 Depth-first traversing of a tree func (t *Tree) Dfs(f func(*Tree)) {
pub struct Tree<V> {
def DFS(f, root):
traverse(Tree nod
Call a function f on every node of a tree, in if t == nil {
children: Vec<Tree<V>>,
f(root)
e, f(value)) {

depth-first prefix order return


value: V
for child in roo f(node.value);

}
}
t:
for (var child i
f(t)
DFS(f, ch n node.children) {

for _, child := range t.Children {


impl<V> Tree<V> {
ild) traverse(chil
child.Dfs(f)
pub fn dfs<F: Fn(&V)>(& d, f);

}
self, f: F) {
}

} self.dfs_helper(& }
The function f is a parameter of the traversal f);

method Dfs .
}

The traversal is prefix because f is applied to fn dfs_helper<F: Fn(&V)


current node first. >(&self, f: &F) {

(f)(&self.value);

for child in &self.


children {

child.dfs_helpe
r(f)

// ...

}
The actual idiomatic way to do
this is to implement an iterator.

Go
Rust
Python
Kotlin
Scala
Dart
19 Reverse a list for i, j := 0, len(x)-1; i < j; i, j = i+1, let y: Vec<_> = x.into_iter x = reversed(x) x.reverse() val items = List(1, x = x.reversed.toL
Reverse the order of the elements of list x.
j-1 {
().rev().collect(); 2, 3, 4, 5)
ist();
returns an iterable.
MutableLists or
This may reverse "in-place" and destroy the x[i], x[j] = x[j], x[i]
items.reverse
x is left unchanged.
on lists this creates a new list. Arrays can be
original ordering. } reversed in place.
This loop reverts "in-place" (in the original list, not Works with other data structures Alternative implementation:
creating a new one). that implement Iterator. y = x[::-1] Alternative
implementation:
Creates a new, reversed list.
Alternative implementation: x.reversed()
x.reverse(); Alternative implementation: Immutable lists but
x has type Vec.
x.reverse() not in-place.
Reverses list in place
This reverses in place. Alternative
implementation:
val reversedView
= x.asReversed()

Returns a reversed
read-only view of the
original List. All
changes made in the
original list will be
reflected in the
reversed one.
20 Return two values func search(m [][]int, x int) (bool, int, i fn search<T: Eq>(m: &Vec<Ve def search(m, x):
fun search(m: Arr def search[T](m: Iter class Position {

Implement a function search which looks for item nt) {


c<T>>, x: &T) -> Option<(us for idx, item in enum ay<Array<Int>>, able[Iterable[T]], x: int i, j;

x in a 2D matrix m.
for i := range m {
ize, usize)> {
erate(m):
x: Int): Pair<In T): Option[(Int, In Position(this.i,
Return indices i, j of the matching cell.
for j, v := range m[i] {
for (i, row) in m.iter if x in item:
t, Int>? {
t)] = {
this.j);

Think of the most idiomatic way in the language if v == x {


().enumerate() {
return idx, i m.forEachInde for ((row, i) <- m. }

to return the two values at the same time. return tru for (j, column) in tem.index(x) xed { i, row ->
view.zipWithIndex; (c Position search(Li
e, i, j
row.iter().enumerate() {
row.forEa olumn, j) <- row.vie st<List> m, x) {

}
if *column == * chIndexed { j, va w.zipWithIndex if col for (var i = 0;
}
x {
lue ->
umn == x)
i < m.length; i++)
}
return Some if (v return Some((i, {

return false, 0, 0
((i, j));
alue == x) {
j))
var line = m
} }
r None
[i];

Go functions may return multiple values.


}
eturn Pair(i, j)
} for (var j =

This function returns 3 values : one to indicate if x }


}
Note: This will refuse to 0; j < line.lengt
was found or not, and two for the coordinates. }
work on Array h; j++) {

None
}
if (line[j]
} return null
== x) {

This returns an optional tuple. } return new


Position(i, j);

return null;

}

Go
Rust
Python
Kotlin
Scala
Dart
21 Swap values a, b = b, a std::mem::swap(&mut a, &mut a, b = b, a a = b.also { b = val tmp = a
var tmp = a;

Swap the values of the variables a and b b);


a } a = b
a = b;

b = tmp
b = tmp;
Alternative implementation:
let (a, b) = (b, a);
This uses pattern matching and
destructuring of tuples to swap
values.
22 Convert string to integer import "strconv" let i = s.parse::<i32>().un i = int(s) val i = s.toInt() s.toInt var i = int.parse
Extract the integer value i from its string wrap(); (s);
representation s (in radix 10) i, err := strconv.Atoi(s)
This panics if s is not a valid Alternative
Atoi(s) is shorthand for ParseInt(s, 10, 0). It yields implementation:
number.

type int.
s is parsed to 32-bits signed val i = s.toIntOr
Alternative implementation: integer here (change number Null()
type if needed). i is null if s can not
import "strconv"
be converted to an
i, err := strconv.ParseInt(s, 10, 0) Alternative implementation:
integer
Radix 10. Third argument 0 means "fit in let i: i32 = s.parse().unwr
implementation-specific int". But result type is ap_or(0);
always int64.
This explicitly sets the value to 0
Don't ignore the potential error err ! if it can't be parsed to an integer.

Alternative implementation:
let i = match s.parse::<i32
>() {

Ok(i) => i,

Err(_e) => -1,

};
s is parsed to 32-bits signed
integer here (change number
type if needed).

-1 is used here as a fallback


value, but any error handling
instructions can be used.
23 Convert real number to string with 2 decimal import "fmt" let s = format!("{:.2}", s = '{:.2f}'.format(x) s = "%.2f".format var s = x.toString
places x); (x) AsFixed(2);
Given a real number x, create its string s := fmt.Sprintf("%.2f", x)
Alternative implementation: Only works up to
representation s with 2 decimal digits following
s = f'{x:.2f}' 1e+21, then it uses
the dot.
f' → a formatted string
exponential notation.
{x: → formatting x to

.2f → a fixed-point number with


2 decimal digits
24 Assign to string the japanese word ネコ s := "ネコ" let s = "ネコ"; s = "ネコ" val s = "ネコ" var s = "ネコ";
Declare a new string s and initialize it with the
UTF-8 literals are valid in Go.
Make sure to always save your
literal value "ネコ" (which means "cat" in
source code files as UTF-8.
japanese)
Also the source code in Go is defined to be UTF-8
text; No other representation is allowed.

Go
Rust
Python
Kotlin
Scala
Dart
25 Send a value to another thread import "fmt" use std::thread;
import Queue import "dart:isola
Share the string value "Alan" with an existing use std::sync::mpsc::channe te";
running process which will then display "Hello, go func() {
q = Queue()

l;
Alan" v := <-ch
sendPort.send("val
fmt.Printf("Hello, %v\n", v)
let (send, recv) = channel t = Thread(target=worker)
ue");
}()
();
t.daemon = True
Ports are used for
t.start()
communicating
ch <- "Alan" thread::spawn(move || {
between individually
The receiver goroutine blocks reading the chan loop {
q.put("Alan") running isolates. The
string named ch.
let msg = recv.recv The Queue module has been receiving isolate has
The current goroutine sends the value to ch.
().unwrap();
renamed to queue in Python 3. created the
A goroutine is like a lightweight green thread. println!("Hello, corresponding
{:?}", msg);
receive-port and
}
passed the send-port
});
to this isolate.

send.send("Alan").unwrap();
The message might not be
printed if the main thread exits
before the thread has written to
stdout.
26 Create a 2-dimensional array const m, n = 3, 4
let mut x = vec![vec![0.0f6 x = [[0] * n for _ in ran val x = Array(m, val x = Array.ofDim[D var x = new List.g
Declare and initialize a matrix x having m rows var x [m][n]float64 4; N]; M]; ge(m)] { DoubleArray(n) ouble](m,n) enerate(m, (_) =>
and n columns, containing real numbers. })
new List(n));
m, n must be constant for this syntax to be valid.
Do not just "multiply by m",
Here x is of type [3][4]float64, it is not a slice. Alternative implementation: which would duplicate the The type of x is
let mut x = [[0.0; N] ; M]; references to the inner arrays. Array<DoubleArray>.
Alternative implementation: In other words, an
This works only when M and N
func make2D(m, n int) [][]float64 {
Alternative implementation: array of arrays.
are constant.

buf := make([]float64, m*n)


Elements have type f64 print(5)

x := make([][]float64, m)

for i := range x {

x[i] = buf[:n:n]

buf = buf[n:]

return x

}
This works even when m, n are not compile-time
constants.

This code allocates one big slice for the numbers,


plus one slice for x itself.

The same function would have to be rewritten, for


types other than float64.

Go
Rust
Python
Kotlin
Scala
Dart
27 Create a 3-dimensional array const m, n, p = 2, 2, 3
let x = vec![vec![vec![0.0f x = [[[0 for k in range val x = Array(m, var x = new List.g
Declare and initialize a 3D array x, having var x [m][n][p]float64 64; p]; n]; m]; (p)] for j in range(n)] f { Array(n, { Doub enerate(m, (_) =>

dimensions boundaries m, n, p, and containing or i in range(m)] leArray(p) } ) } ne


m, n, p must be constant for this syntax to be valid.
m, n, p don't have to be
real numbers. ) w List.generate(n,
Here x is of type [2][2][3]float64, it is not a slice. constants xrange is not supported in
Python 3.7 (_) =>

Alternative implementation: Alternative implementation:


func make3D(m, n, p int) [][][]float64 {
let x = [[[0.0f64; P]; N]; Alternative implementation: new List.filled(p,
buf := make([]float64, m*n*p)
M]; import numpy 0.0),

Stack-allocated array.
x = numpy.zeros((m,n,p))
x := make([][][]float64, m)
growable: false),

for i := range x {
NumPy is a third-party library gr
M, N, P are constants.
x[i] = make([][]float64, n)
for scientific computing. owable: false);
for j := range x[i] {
Dart does not have
x[i][j] = buf[:p:p]
multidimensional
buf = buf[p:]
arrays as a primitive,
}
this is a list of lists of
}
lists of doubles, all
return x
fixed-length lists.
}
This works even when m, n, p are not compile-time
constants.

This code allocates one big slice for the numbers,


then a few slices for intermediate dimensions.

To same function would be rewritten, for types


other than float64.
28 Sort by a property import "sort" items.sort_by(|a,b| a.p.cmp items = sorted(items, key items.sortedBy { case class S(x: Int)
items.sort((a, b)
Sort elements of array-like collection items in (&b.p)); =lambda x: x.p) it.p }
val items = List(S => Comparable.comp
ascending order of x.p, where p is a field of the type ItemPSorter []Item

The lambda expression pulls (3), S(4), S(2))


are(a.p, b.p));
type Item of the objects in items. func (s ItemPSorter) Len() int{ return len
Alternative implementation: out the field you want to sort items.sortBy( item: S
(s) }

items.sort_by_key(|x| x.p); by. If you want to sort in => item.x ) Alternative


func (s ItemPSorter) Less(i,j int) bool{ re
reverse order, add implementation:
turn s[i].p<s[j].p }

reverse=True to the argument Alternative items.sort((a, b)


func (s ItemPSorter) Swap(i,j int) { s[i],s
list. implementation: => (a.p).compareTo
[j] = s[j],s[i] }

items.sortBy(_.x) (b.p));
Alternative implementation:
func sortItems(items []Item){

sorter := ItemPSorter(items)
from operator import attr
sort.Sort(sorter)
getter
} items = sorted(items, key
The standard way is to declare a new type =attrgetter('p'))
ItemSorter as a slice of Item, and carefully We use attrgetter to avoid
implement method Less. having to write a lambda. The
Operator module contains lots
Alternative implementation:
of useful functions that can be
import "sort"
passed to higher-order
less := func(i, j int) bool {
functions.
return items[i].p < items[j].p

sort.Slice(items, less)
This is the diomatic way since Go 1.8.

Go
Rust
Python
Kotlin
Scala
Dart
29 Remove item from list, by its index items = append(items[:i], items[i+1:]...) items.remove(i) del items[i] items.removeAt(i) items.removeAt(i);
Remove i-th item from list items.

If items elements are pointers or structs with This alters the original list.
This will alter the original list or return a new list,
pointers, then refer to the SliceTricks page to avoid
depending on which is more idiomatic.

memory leaks.
Note that in most languages, the smallest valid
value for i is 0. Alternative implementation:
copy(items[i:], items[i+1:])

items[len(items)-1] = nil

items = items[:len(items)-1]
This code is for pointer value type, and has no
memory leak.
30 Parallelize execution of 1000 independent import "sync" use std::thread; from multiprocessing impo import kotlinx.co
tasks rt Pool routines.*
Launch the concurrent execution of procedure f wg := sync.WaitGroup{}
let threads: Vec<_> = (0..1
with parameter i from 1 to 1000.
wg.Add(1000)
000).map(|i| {
pool = Pool()
fun main() = runB
Tasks are independent and f(i) doesn't return any for i := 1; i <= 1000; i++ {
thread::spawn(move for i in range(1, 1001):
locking {

value.
go func(j int) {
|| f(i))
pool.apply_async repeat(1000)
Tasks need not run all at the same time, so you f(j)
}).collect();
(f, [i]) {

may use a pool. wg.Done()


launch {

}(i)
for thread in threads {
f(it)

}
thread.join();
}

wg.Wait() } }

The current value of i is captured, and a goroutine If you don't join the threads, the }
is launched program will just exit and the
threads will be killed.

This would be better


implemented with a thread pool
but the standard library doesn't
include one.

Alternative implementation:
extern crate rayon;

use rayon::prelude::*;

(0..1000).into_par_iter().f
or_each(f);
Requires the rayon crate.

(https://crates.io/crates/rayon)

Go
Rust
Python
Kotlin
Scala
Dart
31 Recursive factorial (simple) func f(i int) int {
fn f(n: u32) -> u32 {
def f(i):
fun f(i: Int): In def f(i: Int): Int =
f(i) => (i == 0) ?
Create the recursive function f which returns the if i == 0 {
if n < 2 {
if i == 0:
t = when (i) {
if (i > 1){
1 : i * f(i - 1);
factorial of the non-negative integer i, calculated return 1
1
return 1
0 -> 1
i * f(i-1)

from f(i-1) }
} else {
else:
else -> i * f } else{

return i * f(i-1)
n * f(n - 1)
return i * f(i-1) (i - 1)
1

} }
}
}
}
Alternative
Alternative implementation: implementation:
fn factorial(num: u64) -> u fun f(i: Int) = i
64 {
f (i == 0) 1 else
match num {
i * f(i - 1)

0 | 1 => 1,

_ => factorial(num
- 1) * num,

}
match arm for 0|1 checks if the
numbers are either 0 or 1

Go
Rust
Python
Kotlin
Scala
Dart
32 Integer exponentiation by squaring func exp(x, n int) int {
fn exp(x: u64, n: u64) -> u def exp(x, n):
fun exp(x: Int, def exp(x: Int, n: In int exp(int x, int
Create function exp which calculates (fast) the switch {
64 {
return x**n
n: Int): Int = wh t): Int {
n) {

value x power n.
case n == 0:
match n {
en {
if(n == 0) {
if (n == 0) retu
x and n are non-negative integers. return 1
0 => 1,
n == 0 -> 1
1
rn 1;

case n == 1:
1 => x,
n == 1 -> x
} else if(n == 1) {
if (n == 1) retu
return x
i if i % 2 == 0 => n % 2 == 0 -> x
rn x;

case n%2 == 0:
exp(x * x, n / 2),
exp(x * x, n / 2)
} else if(n%2 == 0) var r = exp(x *
return exp(x*x, n/2)
_ => x * exp(x * x, else -> x * e {
x, n ~/ 2);

default:
(n - 1) / 2),
xp(x * x, (n - 1) exp(x*x, n/2)
if (n % 2 == 1)
return x * exp(x*x, (n-1)/ }
/ 2)
} else {
r *= x;

2)
} } x * exp(x*x, (n- return r;

}
1)/2)
}
} }

Warning: type int quickly overflows } Alternative


This isn't tail recursive implementation:
because of the last else int exp(int x, int
branch. n) {

var r = 1;

while (true) {

if (n.isOdd) r
*= x;

n ~/= 2;

if (n == 0) br
eak;

x *= x;

return r;

}
The idiomatic way to
do exponentiation by
squaring is a loop, not
a recursive function.

This one puts the


break before the x*=x
to avoid an extra
unnecessary
multiplication at the
end.

Go
Rust
Python
Kotlin
Scala
Dart
33 Atomically read and update variable import "sync" let mut x = x.lock().unwrap import threading x = f(x);
Assign to the variable x the new value f(x), ();

var lock sync.RWMutex


lock = threading.Lock()
Dart is single-
making sure that no other thread may modify x *x = f(x); threaded. Other
between the read and the write.
lock.Lock()
Assuming x is created like this:
lock.acquire()
threads run in
x = f(x)
`let x = Mutex::new(0);` try:
separate isolates.

lock.Unlock() x = f(x)

You need to lock whenever accessing x. finally:

lock.release()

Alternative implementation:
import threading

with threading.Lock():

x = f(x)

34 Create a set of objects x := make(map[T]bool) use std::collections::HashS class T(object):


val x = Set[T]() var x = new Set<T>
Declare and initialize a set x containing unique et; pass
();
There is no built-in Set type, but you can create a The default
objects of type T.
Map with key type T and boolean value (which will let x: HashSet<T> = HashSe implementation of Set is
be ignored). x = set(T()) a HashSet
t::new();

Alternative implementation: Alternative implementation:


x := make(map[T]struct{}) class T:

The struct{} type is space efficient because it ...

occupies zero bytes in memory.

But it is less intuitive to use than a bool value. s = set(T() for _ in rang
e(x))

`...` is a placeholder, `pass` can


also be used

Go
Rust
Python
Kotlin
Scala
Dart
35 First-class function : compose func compose(f func(A) B, g func(B) C) func fn compose<'a, A, B, C, G, def compose(f, g):
typedef R Func<T,R
Implement a function compose (A -> C) with (A) C {
F>(f: F, g: G) -> Box<Fn(A) return lambda a: g(f >(T arg);

parameters f (A -> B) and g (B -> C), which return func(x A) C {


-> C + 'a>
(a))
returns composition function g ∘ f return g(f(x))
where F: 'a + Fn(A) Func<A,C> compose
We could have used a named
}
-> B, G: 'a + Fn(B) -> C
function but a lambda is shorter (B f(A x), C g(B
} {
x)) => (A x) => g
Functions are first-class citizens in Go. They are Box::new(move |x| g (f(x))
passed as arguments and as return values. (f(x)))
Function types can be
} written directly on
Unfortunately, you'll need to parameters, but not in
implement another two variants the return type, so it
if you care about FnMut and needs a typedef to
FnOnce. Also, for now, you declare the types of
need to box the returned this function.

function. In the future, this


shouldn't be necessary. Without the types it's
just:

Alternative implementation: compose(f,g)=>


fn compose<A, B, C>(f: impl (x)=>g(f(x));

Fn(A) -> B, g: impl Fn(B) -


> C) -> impl Fn(A) -> C {

move |x| g(f(x))

36 First-class function : generic composition func composeIntFuncs(f func(int) int, g fun fn compose<'a, A, B, C, G, def compose(f, g):
compose(f, g) =>
Implement a function compose which returns c(int) int) func(int) int {
F>(f: F, g: G) -> Box<Fn(A) return lambda x: (x) => g(f(x));
composition function g ∘ f for any functions f and return func(x int) int {
-> C + 'a>
g(f(x))
g having exactly 1 parameter. return g(f(x))
where F: 'a + Fn(A) This is the same as for non-
}
-> B, G: 'a + Fn(B) -> C
generic composition
} {

Go doesn't have support for generics so the Box::new(move |x| g


functions must take and return concrete types.
(f(x)))

}
It could be done with an empty interface, but that Unfortunately, you'll need to
would discard static type checks (the implement another two variants
implementations of f and g can still be type- if you care about FnMut and
checked, though). FnOnce. Also, for now, you
need to box the returned
function. In the future, this
shouldn't be necessary.

Alternative implementation:
fn compose<A, B, C>(f: impl
Fn(A) -> B, g: impl Fn(B) -
> C) -> impl Fn(A) -> C {

move |x| g(f(x))

}

Go
Rust
Python
Kotlin
Scala
Dart
37 Currying type PayFactory func(Company, *Employee, *E fn add(a: u32, b: u32) -> u from functools import par def add(x: Int)(y: In
Transform a function that takes multiple mployee) Payroll
32 {
tial t) = x + y

arguments into a function for which some of the curry(f(a, b), a)


a + b
val add5 = add(5)

arguments are preset. def f(a):


=> (b) => f(a, b);
type CustomPayFactory func(*Employee) Payro }
val seven = add5(2)
return lambda b: Simple currying of
ll
With only single
a+b
binary funtion.
let add5 = move |x| add(5, parameter list (technically
func CurryPayFactory(pf PayFactory,company x);
not currying)
print (f(2)(1))

Company, boss *Employee) CustomPayFactory {

return func(e *Employee) Payroll {


Alternative
#add_to_two = partial(f,
return pf(company, boss, e)
implementation:
2)
}
def add(x: Int)(y: In
} t) = x + y

The currying function is not generic, it must be val add5 = add(5)_


written for each type of currying needed. With multiple parameter
lists. (add5 takes the 1
parameter of the other
parameter list)
38 Extract a substring t := string([]rune(s)[i:j]) extern crate unicode_segmen t = s[i:j] val t = s.substri var t = s.substrin
Find substring t consisting in characters i tation;
ng(i, j) g(i, j);
convert to []rune because some characters are two Slicing works on strings.
(included) to j (excluded) of string s.
use unicode_segmentation::U
or more bytes.
Character indices start at 0 unless specified nicodeSegmentation;
otherwise.

Make sure that multibyte characters are properly let t = s.graphemes(true).s


handled. kip(i).take(j - i).collec
t::<String>();
Treats the 'character indexes' as
indices of 'extended grapheme
clusters' as defined by Unicode.

Alternative implementation:
use substring::Substring;

let t = s.substring(i, j);

39 Check if string contains a word import "strings" let ok = s.contains(word); ok = word in s val ok = s.contai val ok = s.contains(w var ok = s.contain
Set boolean ok to true if string word is contained ns(word) ord) s(word);
in string s as a substring, or to false otherwise. ok := strings.Contains(s, word)
s and word have type Argument of contains
java.lang.String must be a Pattern.

Go
Rust
Python
Kotlin
Scala
Dart
40 Graph with adjacency lists type Vertex struct{
from collections import d inline class Vert
Declare a Graph data structure in which each Id int
efaultdict exId(val id: Int)

Vertex has a collection of its neighbouring Label string


data class Vertex
vertices. class Vertex(set): pass

Neighbours map[*Vertex]bool
(val id: VertexI
class Graph(defaultdict):

}
d, val neighbour
def __init__(self, *pat
s: Set<VertexId>)

hs):

type Graph []*Vertex data class Graph


self.default_factory
The map is used as a Set of Vertex pointers.
(val vertices: Se
= Vertex

Graph is a list of all the Vertex pointers. t<Vertex>)


for path in paths:

self.make_path(pat
h)

def make_path(self, lab


els):

for l1, l2 in zip(lab


els, labels[1:]):

self[l1].add(l2)

self[l2].add(l1)

G = Graph((0, 1, 2, 3),
(1, 4, 2))

41 Reverse a string runes := []rune(s)


let t = s.chars().rev().col t = s.decode('utf8')[::- val t = s.reverse s.reverse var t = new Strin
Create string t containing the same characters as for i, j := 0, len(runes)-1; i < j; i, j = lect::<String>(); 1].encode('utf8') d() g.fromCharCodes(s.
string s, in reverse order.
i+1, j-1 {
runes.toList().rev
collect is a function with a
Original string s must remain unaltered. Each runes[i], runes[j] = runes[j], runes[i]
generic return type, so we must Alternative implementation: ersed);
character must be handled correctly regardless }
explicitly specify that we want a t = s[::-1] This does reverse the
its number of bytes in memory. t := string(runes) String back, either by annotating order of the runes,
This takes care of multi-byte runes, which count as t's type as a String, or by however it may handle
a single character. specifying with the so-called improperly some
"turbofish" syntax. dependant runes like
diacritics.
Alternative implementation:
let t: String = s.chars().r Alternative
ev().collect(); implementation:
var t = s.split
('').reversed.join
();


Go
Rust
Python
Kotlin
Scala
Dart
42 Continue outer loop mainloop:
'outer: for va in &a {
for v in a:
main() {

Print each item v of list a which is not contained for _, v := range a {


for vb in &b {
try:
var a = [1, 2,
in list b.
for _, w := range b {
if va == vb {
for u in b:
3];

For this, write an outer loop to iterate on a and an if v == w {


continue 'oute if v == u:
var b = [2, 3];

inner loop to iterate on b. continue ma r;


raise Exc
inloop
}
eption()
outer: for (var
}
}
print(v)
v in a) {

}
println!("{}", va);
except Exception:
for (var w in
fmt.Println(v)
}
continue
b) {

} 'outer is a label used to refer to Note that using two loops like if (w == v)
mainloop is a label used to refer to the outer loop. the outer loop. Labels in Rust this in python is by itself very continue outer;

start with a '. un-idiomatic. Also one would }

be wise to define a custom print(v);

exception to avoid hiding "real" }

exceptions. }

43 Break outer loop mainloop:


'outer: for v in m {
class BreakOuterLoop (Exc OUTER: for (var i
Look for a negative value v in 2D integer matrix for i, line := range m {
'inner: for i in v {
eption): pass
= 0; i < m.length;
m. Print it and stop searching. for _, v := range line {
if i < 0 {
i++) {

if v < 0 { println!("Found try:


for (var j = 0;
fmt.Println {}", i);
position = None
j < m[i].length; j
(v)
break 'outer;
for row in m:
++) {

break mainl }
for column in m[r if (m[i][j] <
oop
}
ow]:
0) {

}
} if m[row][col print("Negat
}
Loop label syntax is similar to umn] == v:
ive value found at
} lifetimes. position $i,$j: ${m[i]
mainloop is a label used to refer to the outer loop. = (row, column)
[j]}");

raise Bre break OUTER;

akOuterLoop
}

except BreakOuterLoop:
}

pass }
This is ugly because the
pythonic way to solve this
problem would be to refactor
so that one doesn't have to
break out of multiple loops.
See PEP3136

Alternative implementation:

Go
Rust
Python
Kotlin
Scala
Dart
def loop_breaking(m, v):

for i, row in enumera


te(m):

for j, value in e
numerate(row):

if value ==
v:

return
(i, j)

return None

print(loop_breaking(([1,
2,3],[4,5,6],[7,8,9]),
6))
Rather than set break flags, it
is better to refactor into a
function, then use return to
break from all nested loops.

Alternative implementation:
from itertools import cha
in

matrix = [[1,2,3],[4,-5,
6],[7,8,9]]

try:

print(next(i for i in
chain.from_iterable(matri
x) if i < 0))

except StopIteration:

pass
We make a generator that will
return negative values from a
list (and use
chain.from_iterable(matrix) to
lazily extract the values) and
only take one value from it with
the next function. The
generator will not continue until
we call next again.

This will raise StopIteration if it


doesn't find the value so we
need to account for it.
44 Insert element in list s = append(s, 0)
s.insert(i, x); s.insert(i, x) s.insert(i, x);
Insert element x at position i in list s. Further copy(s[i+1:], s[i:])

elements must be shifted to the right. s[i] = x


Extend slice by 1 (it may trigger a copy of the
underlying array).

Then shift elements to the right.

Then set s[i].



Go
Rust
Python
Kotlin
Scala
Dart
45 Pause execution for 5 seconds import "time" use std::{thread, time}; import time Thread.sleep(5000 Thread.sleep(5000) import 'dart:io';
Sleep for 5 seconds in current thread, before L)
proceeding with the next instructions. time.Sleep(5 * time.Second) thread::sleep(time::Duratio time.sleep(5) sleep(const Durati
Unit is Duration, an alias for int64 representing a n::from_secs(5)); on(seconds: 5));
number of nanoseconds.
sleep is only available
The constant Second helps readability. if dart:io is available
(ie. on server side)

Attention! sleep stops


all asynchronous
execution within the
whole Isolate, e.g. will
stop all updates for
the complete Flutter
GUI for that time.

Alternative
implementation:
import "dart:asyn
c";

await new Future.d


elayed(const Durat
ion(seconds : 5));
Waiting makes sense
in asynchronous code.
It's not done that
often, and there is no
simple primitive for it.

This will not pause the


*thread*, but will delay
the rest of the current
async function.

Go
Rust
Python
Kotlin
Scala
Dart
46 Extract beginning of string (prefix) t := string([]rune(s)[:5]) let t = s.char_indices().nt t = s[:5] val t = s.take(5) val t = s.take(5) var t = s.substrin
Create string t consisting of the 5 first characters h(5).map_or(s, |(i, _)| &s g(0, 5);
This "incurs a run-time cost" proportional to len(s).
of string s.
[..i]);
Make sure that multibyte characters are properly
Rust strings are encoded in
handled.
UTF-8, and can be multiple
bytes wide, which text
processing code must account
for. Naively slicing the string
could cause it to panic if, for
example, the string contained
😁

It should be noted that these


logical "characters" don't have
much semantic meaning either:
Unicode characters are
combined into "graphemes"
before being displayed to the
user, which would need to be
identified using the unicode-
segmentation crate

Alternative implementation:
let t = s.chars().take(5).c
ollect::<String>();

47 Extract string suffix t := string([]rune(s)[len([]rune(s))-5:]) let last5ch = s.chars().cou t = s[-5:] var n = s.length;

Create string t consisting in the 5 last characters nt() - 5;


var t = s.substrin
Convert to []rune because some characters are
of string s.
let t: String = s.chars().s g(n-5, n);
two or more bytes long.
Make sure that multibyte characters are properly kip(last5ch).collect();

handled.
48 Multi-line string literal s := `Huey
let s = "line 1
s = """Huey
val s =
val s = """line 1
var s = '''A

Assign to variable s a string literal consisting in Dewey


line 2
Dewey
"""
line 2
multi-line

several lines of text, including newlines. Louie` line 3"; Louie""" This is my
line 3""" string''';
This is a raw string literal (not "interpreted"). multi-line st Triple simple quotes.
Alternative implementation: ring.
Alternative
let s = r#"Huey
""" implementation: Alternative
Dewey
val s = """line 1
implementation:
Louie"#; |line 2
var s = """A

Raw string literals do not |line 3""". multi-line

process any escapes. stripMargin string""";

Using stripMargin to Triple double quotes.


declare indented multi-
line strings.

Go
Rust
Python
Kotlin
Scala
Dart
49 Split a space-separated string import "strings" let chunks: Vec<_> = s.spli chunks = s.split() val chunks = s.sp val chunks = s.split s.split(new RegExp
Build list chunks consisting in substrings of input t_whitespace().collect(); lit("\\s+".toRege (" ") ('\\s+'))
chunks := strings.Split(s, " ") If sep is not specified or is
string s, separated by one or more space x())
This regards all whitespace as None, a different splitting
characters. chunks has type []string.

separators, including \t and \n. algorithm is applied: runs of


Warning: you may get empty strings as items in
consecutive ASCII whitespace
chunks because of leading spaces, trailing Alternative implementation: are regarded as a single
spaces, and repeated spaces.
let chunks: Vec<_> = s.spli separator, and the result will
Alternative implementation: t_ascii_whitespace().collec contain no empty strings at the
import "strings"
t(); start or end if the sequence
This regards all ASCII has leading or trailing
chunks := strings.Fields(s) whitespace. Consequently,
whitespace as separators,
chunks has type []string.
including \t and \n. splitting an empty sequence or
Fields treats repeated spaces as a single a sequence consisting solely of
separator. Alternative implementation: ASCII whitespace without a
let chunks: Vec<_> = s.spli specified separator returns [].
t(' ').collect();
Warning: this returns some
empty strings in chunks, in case
of multiple consecutive spaces
in the s.
50 Make an infinite loop for {
loop {
while True:
while (true) { } while(true){
while (true) {

Write a loop that has no end clause. // Do something


// Do something
pass println(3)
// do something

} } } }
No need to write loop variables nor end condition.
Alternative
implementation:
for (;;) {

51 Check if map contains key _, ok := m[k] use std::collections::HashM k in m m.containsKey(k) m.contains(k) m.containsKey(k)
Determine whether map m contains an entry for ap;
ok is true if m contains a value for key k. The value returns a Boolean
key k
itself is ignored. m.contains_key(&k)
Same method name for
HashMap and BTreeMap.
52 Check if map contains value func containsValue(m map[K]T, v T) bool {
use std::collections::BTree v in m.values() m.containsValue m.valuesIterator.cont m.containsValue
Determine whether the map m contains an entry for _, x := range m {
Map; (v) ains(v) (v);
with the value v, for some key. if x == v {

let does_contain = m.values


return true

().any(|&val| *val == v);


}

}
Works the same for HashMap.
return false

}
You have to iterate explicitly. Also, this works only
for types K, T (not generic).

Go
Rust
Python
Kotlin
Scala
Dart
53 Join a list of strings import "strings" let y = x.join(", "); y = ', '.join(x)
val y = listOf val y = x.mkString y = x.join(', ');
Concatenate elements of string list x joined by (x).joinToString (",")
y := strings.Join(x, ", ") Note that join() used to be This works if x contains only
the separator ", " to create a single string y. (", ")
named connect() . strings.
This works only if x has type []string.
Alternative implementation:
y = ', '.join(map(str,
x))
This works even if some
elements in x are not strings.
54 Compute sum of integers s := 0
x.iter().sum() s = sum(x) val numbers = lis val s = x.sum() var s = x.fold(0,
Calculate the sum s of the integer list or array x. for _, v := range x {
tOf(1, 2, 3, 4)
(a, b) => a + b);
sum is a built-in function.
s += v
Alternative implementation: val sum = number
} let s = x.iter().sum::<i32> s.sum()
Such explicit loops are idiomatic in Go. ();

55 Convert integer to string import "strconv" let s = i.to_string(); s = str(i) val s = i.toStrin val s = i.toString var s = "$i";

Create the string representation s (in radix 10) of g()


s := strconv.Itoa(i) s has type String
integer value i.
When i has type int. Alternative implementation:

Alternative implementation: let s = format!("{}", i);

import "strconv" s has type String

s := strconv.FormatInt(i, 10)
When i has type int64.

Alternative implementation:
import "fmt"

s := fmt.Sprintf("%d", i)
This works with all types of integers.

Sprintf does type assertions, and is slower than


the strconv flavors

Go
Rust
Python
Kotlin
Scala
Dart
56 Launch 1000 parallel tasks and wait for import "sync" use std::thread; from multiprocessing impo import kotlinx.co
completion rt Pool routines.*
Fork-join : launch the concurrent execution of var wg sync.WaitGroup
let threads: Vec<_> = (0..1
procedure f with parameter i from 1 to 1000.
wg.Add(1000)
000).map(|i| thread::spawn def f(i):
(1..1000)

Tasks are independent and f(i) doesn't return any for i := 1; i <= 1000; i++ {
(move || f(i))).collect();
i * i
.map { i ->

value.
go func(i int) {
Coroutine
Tasks need not run all at the same time, so you f(i)
for t in threads {
with Pool(1000) as p:
Scope(Dispatcher
may use a pool.
wg.Done()
t.join();
p.map(func=f, ite s.Default).async
Wait for the completion of the 1000 tasks and }(i)
}
rable=range(1, 1001))
{

then print "Finished". }


f(i)

wg.Wait()
print('Finished') }

fmt.Println("Finished") }

It is necessary to capture the current value of loop .awaitAll()

variable i. See print("Finished")


https://github.com/golang/go/wiki/CommonMistakes Leverages kotlin's
coroutines to run
1000 tasks in parallel
using a job pool
about the size of the
computer's cpu core
count.

Must be run from


inside a coroutine
context, eg.
runBlocking { /* here
*/ }

Go
Rust
Python
Kotlin
Scala
Dart
57 Filter list y := make([]T, 0, len(x))
let y: Vec<_> = x.iter().fi y = list(filter(p, x)) val y = x.filter val y = x.filter(p) var y = x.where
Create the list y containing the items from the list for _, v := range x{
lter(p).collect(); (p) (p).toList();
filter returns an iterator.
x that satisfy the predicate p. Respect the if p(v){
This collects into a vector (other
original ordering. Don't modify x in-place. y = append(y, v)
Alternative implementation:
collections are possible)
}
y = [element for element
} in x if p(element)]
For item type T. List comprehensions tend to be
Note that this allocates memory for the new slice y.
more readable than filter
Warning: y is allocated with as much memory as x, function
which may in some cases be wasteful.

Alternative implementation:
n := 0

for _, v := range x {

if p(v) {

n++

y := make([]T, 0, n)

for _, v := range x {

if p(v) {

y = append(y, v)

}
This makes 2 passes: one to count the number n of
elements to be kept, and one to copy the elements
in the target slice created with the correct size n.

This is efficient if p is cheap and x is small.


58 Extract file content to a string import "io/ioutil" use std::io::prelude::*;
lines = open(f).read() import java.io.Fi import scala.io.Sourc import "dart:io";
Create string lines from the content of the file use std::fs::File; le e
b, err := ioutil.ReadFile(f)
For more complicated file var lines = new Fi
with filename f.
if err != nil {
let mut file = File::open operations, use a context File(f).readText val lines = Source.fr le(f).readAsString
// Handle error...
(f)?;
manager with with () omFile(filename).getL Sync();
}
let mut lines = String::new ines().mkString("\n") Defaults to UTF-8
Alternative implementation:
lines := string(b) ();
encoding.

file.read_to_string(&mut li with open(f) as fo:

In Go it is idiomatic to inspect an error value before To get lines directly,


nes)?; lines = fo.read()
moving on.
use:

The with statement creates a file.readAsLinesSync()


lines is a single string. Alternative implementation: contextmanager, which
use std::fs; automatically handles closing
the file for you when you're
let lines = fs::read_to_str
done. Without this, you should
ing(f).expect("Can't read f
be manually closing file objects
ile.");
so that you are not relying on
the garbage collector to do this
for you.

Go
Rust
Python
Kotlin
Scala
Dart
59 Write to standard error stream import "os" eprintln!("{} is negative", import sys System.err.printl System.err.println import "dart:io";
Print the message "x is negative" to standard x); n("$x is negativ (s"$x is negative")
error (stderr), with integer x value substitution fmt.Fprintln(os.Stderr, x, "is negative") print(x, "is negative", f stderr.write("$x i
e")

(e.g. "-2 is negative"). ile=sys.stderr) s negative");


Python3

Alternative implementation:
import sys

print >>sys.stderr, "%s i


s negative" % x
Python2

If possible, use the python3


with "from _future__ import
print_function"
60 Read command line argument import "os" use std::env; import sys main(args) {

Assign to x the string value of the first command var x = args[0];

line parameter, after the program name. x := os.Args[1] let first_arg = env::args x = sys.argv[1]
}
os.Args[0] is actually the executable name. ().skip(1).next();
argv[0] is the program name
Command line
let fallback = "".to_owned arguments are only
();
available as argument
let x = first_arg.unwrap_or to main.
(fallback);
The first CLI argument may not
be present. We fall back to an
empty string.

Alternative implementation:
use std::env;

let x = env::args().nth(1).
unwrap_or("".to_string());
We get the 1st element using the
nth method and we fallback to
an empty string if no arg was
found.
61 Get current date import "time" extern crate time; import datetime var d = DateTime.n
Assign to variable d the current date/time value, ow();

in the most standard type. d := time.Now() let d = time::now(); d = datetime.datetime.now


The type Time wraps a timestamp with The current time in the local ()
nanosecond precision. timezone in this format:
http://doc.rust-
lang.org/time/time/struct.Tm.html

Alternative implementation:
use std::time::SystemTime;

let d = SystemTime::now();

Go
Rust
Python
Kotlin
Scala
Dart
62 Find substring position import "strings" let i = x.find(y); i = x.find(y) var i = x.indexOf
Set i to the first position of string y inside string x, (y);
i := strings.Index(x, y) i is an Option<usize>.
find returns the character
if exists.

Finds the byte index of y in x index of y in x, or -1 if not


i is the byte index of y in x, not the character
(not the character index). found.
Specify if i should be regarded as a character (rune) index.

index or as a byte index.

i will be -1 if y is not found in x.


Explain the behavior when y is not contained in
x.
63 Replace fragment of a string import "strings" let x2 = x.replace(&y, &z); x2 = x.replace(y, z) var x2 = x.replace
Assign to x2 the value of string x with all All(y, z);
x2 := strings.Replace(x, y, z, -1) Returns a string slice (&str). Add
occurrences of y replaced by z.

.to_string() or .to_owned() to
Assume occurrences of y are not overlapping. -1 means "no limit on the number of replacements".

get a String.
This replaces non-overlapping instances of y.
64 Big integer : value 3 power 247 import "math/big" extern crate num;
x = 3 ** 247 import "dart:mat
Assign to x the value 3^247 use num::bigint::ToBigInt; h";
x := new(big.Int)

x.Exp(big.NewInt(3), big.NewInt(247), nil) let a = 3.to_bigint().unwra var x = pow(3, 24


The nil argument means we don't want a modulo. p();
7);
let x = num::pow(a, 247);

65 Format decimal number import "fmt" let s = format!("{:.1}%", 1 s = '{:.1%}'.format(x) var s = "${(x * 10
From the real value x in [0,1], create its 00.0 * x); 0).toStringAsFixed
.1 means only one digit after
percentage string representation s with one digit s := fmt.Sprintf("%.1f%%", 100.0*x) (1)}%";

decimal point.

after decimal point. E.g. 0.15625 -> "15.6%" The literal % must be doubled.
% handles the "multiplication"
and shows the percentage
sign.

Alternative implementation:
s = f"{x:.01%}"

66 Big integer exponentiation import "math/big" extern crate num; z = x**n import "dart:mat
Calculate the result z of x power n, where x is a h";
big integer and n is a positive integer. nb := big.NewInt(int64(n))
let z = num::pow(x, n);
var z big.Int
var z = pow(x, n);
z.Exp(x, nb, nil)
Exponentiation is already implemented in package
math/big.

Go
Rust
Python
Kotlin
Scala
Dart
67 Binomial coefficient "n choose k" import "math/big" extern crate num;
import math int binom(int n, i
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an nt k) {

integer type able to handle huge numbers. z := new(big.Int)


def binom(n, k):

use num::bigint::BigInt;
int result = 1;

z.Binomial(n, k) return math.factorial


use num::bigint::ToBigInt;
for (int i = 0;
(n) // math.factorial(k)
use num::traits::One; i < k; i++) {

// math.factorial(n - k)
result = resul
fn binom(n: u64, k: u64) ->
t * (n - i) ~/ (i
BigInt {
Alternative implementation:
+ 1);

let mut res = BigInt::o import math


}

ne();

def binom(n, k):


return r;

for i in 0..k {

return math.comb(n, }
res = (res * (n -
i).to_bigint().unwrap()) /
k)
(i + 1).to_bi Python 3.8+
gint().unwrap();

res

68 Create a bitset import "math/big" let mut x = vec![false; n]; from __future__ import di
Create an object x to store n bits (n being vision

potentially large). var x *big.Int = new(big.Int)


import math
big.Int type makes a decent bitset.

It grows automatically when needed. x = bytearray(int(math.ce


il(n / 8.0)))
Alternative implementation:
x := make([]bool, n)
This makes a simple fixed-size bitset.

It uses more bits in memory than the useful size n.

Alternative implementation:
x := make([]uint64, (n+63)/64)
This compact bitset requires some extra logic to
implement get, set, clear (see demo).
69 Seed random generator import "math/rand" use rand::{Rng, SeedableRn import random val random = Rand import "dart:mat
Use seed s to initialize a random generator.
g, rngs::StdRng}; om(seed=s) h";
rand.Seed(s) rand = random.Random(s)
If s is constant, the generator output will be the s is of type int64.
let s = 32;
this creates a new random var r = new Random
same each time the program runs. If s is based This initializes the default Source. let mut rng = StdRng::seed_ generator rand (s);

on the current value of the system clock, the from_u64(s);


generator output will be different each time. Alternative implementation:
import "math/rand"

r := rand.New(rand.NewSource(s))
s is of type int64.

r is of type *rand.Rand.

Go
Rust
Python
Kotlin
Scala
Dart
70 Use clock as random generator seed import "math/rand"
use rand::{Rng, SeedableRn import random var r = new Random
Get the current datetime and provide it as a seed import "time" g, rngs::StdRng};
(new DateTime.now
to a random generator. The generator sequence rand = random.Random()
use std::time::SystemTime; ().millisecondsSin
will be different at each run. rand.Seed(time.Now().UnixNano()) the constructor uses the ceEpoch);
This initializes the default Source. let d = SystemTime::now()
current time if used without
.duration_since(SystemT arguments.

Alternative implementation: ime::UNIX_EPOCH)


you could also use the
import "math/rand"
.expect("Duration since functions of the random
import "time" UNIX_EPOCH failed");
module (they are using a
let mut rng = StdRng::seed_ shared ``Random`` object
r := rand.New(rand.NewSource(time.Now().Uni from_u64(d.as_secs()); which is constructed the first
xNano()))
time random is imported
r is of type *rand.Rand.
71 Echo program implementation import "fmt"
use std::env; import sys fun main(args: Ar println(args.mkString main(List<String>
Basic implementation of the Echo program: Print import "os"
ray<String>) = ar (" ")) args) {

all arguments except the program name, println!("{}", env::args(). print ' '.join(sys.argv
import "strings" gs.forEach(::prin print(args.join
separated by space, followed by newline.
skip(1).collect::<Vec<_>> [1:])
tln) (' '));

The idiom demonstrates how to skip the first func main() {


().join(" "));
}
argument if necessary, concatenate arguments fmt.Println(strings.Join(os.Args[1:], "
as strings, append newline and print it to stdout. "))
Alternative implementation:
} use itertools::Itertools;

println!("{}", std::env::ar
gs().skip(1).format(" "));

73 Create a factory type ParentFactory func(string) Parent


def fact(a_class, str_):

Create a factory named fact for any sub class of if issubclass(a_clas


Parent and taking exactly one string str as var fact ParentFactory = func(str string) P s, Parent):

constructor parameter. arent {


return a_class(st
return Parent{
r_)
name: str,
You can use the class like a
}
function.
}
A Factory is a function which returns an object.

Go doesn't have subtyping, but Parent could be


any type: struct, interface, etc.
74 Compute GCD import "math/big" extern crate num;
from fractions import gcd int gcd(int a, int
Compute the greatest common divisor x of big b) {

integers a and b. Use an integer type able to x.GCD(nil, nil, a, b) x = gcd(a, b)


use num::Integer;
while (b != 0) {

handle huge numbers. The first two arguments can be ignored in this use use num::bigint::BigInt; var t = b;

case.
b = a % t;

let x = a.gcd(&b);
a = t;

x, a, b have pointer type *big.Int . Uses the num crate's Integer }

trait. return a;

}

Go
Rust
Python
Kotlin
Scala
Dart
75 Compute LCM import "math/big" extern crate num;
from math import gcd x = lcm(a, b);

Compute the least common multiple x of big


integers a and b. Use an integer type able to gcd.GCD(nil, nil, a, b)
x = (a*b)//gcd(a, b)
use num::Integer;
int lcm(int a, int
handle huge numbers. x.Div(a, gcd).Mul(x, b)
use num::bigint::BigInt; b) => (a * b) ~/ g
LCM is not in the standard library, but can be cd(a, b);

deduced from GCD.


let x = a.lcm(&b);
Part of the num crate's Integer int gcd(int a, int
gcd divides a, by definition.
trait. b) {

while (b != 0) {

Chaining is permitted and idiomatic.


var t = b;

b = a % t;

a, b, gcd, x have pointer type *big.Int. a = t;

return a;

76 Binary digits from an integer import "strconv" let s = format!("{:b}", x); s = '{:b}'.format(x) var s = x.toRadixS
Create the string s of integer x written in base 2.
tring(2);
s := strconv.FormatInt(x, 2) Formatting lets you choose
another representation (e.g., `b`
E.g. 13 -> "1101" Here x has the type int64.

for binary, `X` for hex in upper


case and `_?` for debug output).
For very big numbers, prefer the type *big.Int.

Alternative implementation:
import "fmt"

import "math/big"

s := fmt.Sprintf("%b", x)
x has the type *big.Int.

This works because *big.Int implements the


fmt.Formatter interface.
77 Complex number x := 3i - 2
extern crate num;
x = 3j-2

Declare a complex x and initialize it with value (3i x *= 1i use num::Complex; y = x * 1j


- 2). Then multiply it by i.
complex128 is a built-in type.
let mut x = Complex::new(-
2, 3);

1i denotes the imaginary unit i. x *= Complex::i();



Go
Rust
Python
Kotlin
Scala
Dart
78 "do while" loop for{
loop {
while True:
do {
do {

Execute a block once, then execute it again as someThing()


doStuff();
do_something()
someThing()
someThing();

long as boolean condition c is true. someOtherThing()


if !c { break; }
if not c:
someOtherThing()
someOtherThing
if !c {
} break } while (c) ();

break
Rust has no do-while loop with } while(c);
}
syntax sugar. Use loop and
} break.
Go has no do while loop, use the for loop, instead.
Alternative implementation:
Alternative implementation: while {

for done := false; !done; {


doStuff();

someThing()
c

someOtherThing()
} { /* EMPTY */ }
done = !c()
Use compound expression for
} the while loop condition.
Explicit loop variable done shows the intent.
79 Convert integer to floating point number y := float64(x) let y = x as f64; y = float(x) double y = x.toDou
Declare the floating point number y and initialize ble();
The cast must be explicit.
it with the value of the integer x .
There is no implicit
conversion so you
have to use toDouble
explicitly, or maybe
better: type y as num
which is the
superclass of double
and int.
80 Truncate floating point number to integer y := int(x) let y = x as i32; y = int(x) int y = x.toInt()
Declare integer y and initialize it with the value of
There is no automatic
floating point number x . Ignore non-integer digits
conversion, so you
of x .
have to explicitly call
Make sure to truncate towards zero: a negative x
toInt on the double.
must yield the closest greater integer (not lesser).
The toInt call
truncates, there are
also ceil, floor and
round methods.
81 Round floating point number to integer import "math" let y = x.round() as i64; y = int(x + 0.5) var y = x.round();

Declare integer y and initialize it with the rounded


y := int(math.Floor(x + 0.5)) This rounds ties "away
value of floating point number x .
from zero", though.
Ties (when the fractional part of x is exactly .5)
must be rounded up (to positive infinity).
82 Count substring occurrences import "strings" let c = s.matches(t).count count = s.count(t)
Find how many times string s contains substring ();
x := strings.Count(s, t) counts non-overlapping
t.

Disjoint matches: overlapping occurrences


Specify if overlapping occurrences are counted. Count counts only the number of non-overlapping
occurrences are not counted.
instances of t.

Go
Rust
Python
Kotlin
Scala
Dart
83 Regex with character repetition import "regexp" extern crate regex;
import re
Declare regular expression r matching strings use regex::Regex;
"http", "htttp", "httttp", etc. r := regexp.MustCompile("htt+p") r = re.compile(r"htt+p")
let r = Regex::new(r"htt+
p").unwrap();
In order to avoid compiling the
regex in every iteration of a loop,
put it in a lazy static or
something.
84 Count bits set in integer binary func PopCountUInt64(i uint64) (c int) {
let c = i.count_ones(); c = bin(i).count("1")
representation i -= (i >> 1) & 0x5555555555555555
i must have an explicit type, i.e.

Count number c of 1s in the integer i in base 2.


i = (i>>2)&0x3333333333333333 + i&0 6i64 or 6usize
x3333333333333333

E.g. i=6 → c=2 i += i >> 4

i &= 0x0f0f0f0f0f0f0f0f

i *= 0x0101010101010101

return int(i >> 56)

func PopCountUInt32(i uint32) (n int) {

i -= (i >> 1) & 0x55555555


i = (i>>2)&0x33333333 + i&0x3333333
3

i += i >> 4

i &= 0x0f0f0f0f

i *= 0x01010101

return int(i >> 24)

}
This was useful only before go 1.9.

See math/bits.OnesCount instead.

Alternative implementation:
import "math/bits"

c := bits.OnesCount(i)
i is a uint.

All OnesCountX functions take unsigned integer


types.
85 Check if integer addition will overflow import "math" fn adding_will_overflow(x: def adding_will_overflow
Write boolean function addingWillOverflow usize, y: usize) -> bool {
(x,y):

which takes two integers x, y and return true if func addingWillOverflow(x int, y int) bool
x.checked_add(y).is_non return False
(x+y) overflows.
{

e()
Python has arbitrary precision
if x > 0 {

} integers so you shouldn't worry


An overflow may be above the max positive return y > math.MaxInt-x

}
checked_add is available for all about overflow.

value, or below the min negative value.


return y < math.MinInt-x
integer types. Also, don't bother coding this
} constant function!

Go
Rust
Python
Kotlin
Scala
Dart
86 Check if integer multiplication will overflow func multiplyWillOverflow(x, y uint64) bool fn multiply_will_overflow def multiplyWillOverflow
Write boolean function multiplyWillOverflow {
(x: i64, y: i64) -> bool {
(x,y):

which takes two integers x, y and return true if if x <= 1 || y <= 1 {


x.checked_mul(y).is_non return False
(x*y) overflows.
return false
e()
Python has arbitrary precision
}
} integers so you shouldn't worry
An overflow may be above the max positive d := x * y
checked_mul is available on all about overflow.

value, or below the min negative value. return d/y != x


integer types Also, don't bother coding this
} constant function!
This holds for uint64, not for signed integers.

Note that the multiplication is performed, then its


result is checked.
87 Stop program import "os" std::process::exit(0); import sys import kotlin.sys
Exit immediately.
tem.exitProcess
os.Exit(0) No destructors on the current sys.exit(1)
If some extra cleanup work is executed by the
stack or any other thread's stack exitProcess(0)
program runtime (not by the OS itself), describe
will be run.
it.
88 Allocate 1M bytes buf := make([]byte, 1_000_000) let buf: Vec<u8> = Vec::wit buf = bytearray(1000000)
Create a new bytes buffer buf of size 1,000,000. h_capacity(1000000);
This creates a slice with all values initialized at
zero. This creates a simple but fast
vector. There is also the
unstable alloc::heap::allocate if
you want to go more low-level.
89 Handle invalid argument return nil, fmt.Errorf("invalid value for enum CustomError { InvalidA raise ValueError("x is in
You've detected that the integer value of x: %v", x) nswer }
valid")
argument x passed to the current function is
The last return parameter of the current function
invalid. Write the idiomatic way to abort the fn do_stuff(x: i32) -> Resu
has type error.

function execution and signal the problem. lt<i32, CustomError> {

It is the caller's responsibility to check if the error is


nil, before using the function's other result values. if x != 42 {

Err(CustomError::In
validAnswer)

} else {

Ok(x)

}
A function that can have invalid
inputs should not panic, but
return a Result. The calling
function can then determine
whether to handle the Err value
or unwrap the Result and turn
every Err into a panic.

Go
Rust
Python
Kotlin
Scala
Dart
90 Read-only outside type Foo struct {
struct Foo {
class Foo(object):

Expose a read-only integer x to the outside world x int


x: usize
def __init__(self):

while being writable inside a structure or a class }


}
self._x = 0

Foo.
func (f *Foo) X() int {
impl Foo {
@property

return f.x
pub fn new(x: usize) -> def x(self):

} Self {
"""

x is private, because it is not capitalized.


Foo { x }
Doc for x

(*Foo).X is a public getter (a read accessor). }


"""

return self._x
pub fn x<'a>(&'a self)
-> &'a usize {

&self.x

pub fn bar(&mut self) {

self.x += 1;

91 Load JSON file into object import "encoding/json"


#[macro_use] extern crate s import json import 'dart:io' s
Read from the file data.json and write its content import "io/ioutil" erde_derive;
how File;

into the object x.


with open("data.json",
extern crate serde_json;
import 'dart:conve
Assume the JSON data is suitable for the type of buffer, err := ioutil.ReadFile("data.json")
"r") as input:

use std::fs::File; rt' show json;


x. if err != nil {
x = json.load(input)
return err
let x = ::serde_json::from_ Map x = json.jsonD
}
reader(File::open("data.jso ecode(await new Fi
err = json.Unmarshal(buffer, &x)
n")?)?; le('data.json').re
if err != nil {
Requires x implements adAsString());
return err
Deserialize from serde.
x is a Map
} Serde is used to create an
buffer is a []byte.
object from data, rather than Alternative
&x is the address of x.
populate an existing object. implementation:
You must check errors after each step. import 'dart:io' s
how File;

Alternative implementation: import 'dart:conve


import "encoding/json" rt' show json;

r, err := os.Open(filename)
Map x = json.jsonD
if err != nil {
ecode(new File('da
return err
ta.json').readAsSt
}
ringSync());
decoder := json.NewDecoder(r)
x is a Map
err = decoder.Decode(&x)

if err != nil {

return err

}
Create and use a *json.Decoder

Go
Rust
Python
Kotlin
Scala
Dart
92 Save object into JSON file import "encoding/json"
extern crate serde_json;
import json import 'dart:io' s
Write the contents of the object x into the file import "io/ioutil" #[macro_use] extern crate s how File;

data.json. with open("data.json",


erde_derive;
import 'dart:conve
buffer, err := json.MarshalIndent(x, "", " "w") as output:

rt' show JSON;


")
json.dump(x, output)
use std::fs::File;
if err != nil {
class JsonModel {

return err
::serde_json::to_writer(&Fi // Create Field

}
le::create("data.json")?, & int id;

err = ioutil.WriteFile("data.json", buffer, x)? String qrText, l


0644) This requires x to implement icen, trans, name;

json.MarshalIndent is more human-readable than Deserialize from serde.


json.Marshal. // // Constructo
r

// JsonModel(

// int idIn
t, String nameStri
ng, String userStr
ing, String passwo
rdString) {

// // id=idIn
t;

// // name =nameSt
ring;

// // user =userSt
ring;

// // password = p
asswordString;

// }

JsonModel(this.i
d, this.name, thi
s.licen, this.tran
s, this.qrText);

JsonModel.fromJs
on(Map<String, dyn
amic> parseJSON) {

id = int.parse
(parseJSON['id']);

licen = parseJ
SON['Li
x is a Map
93 Pass a runnable procedure as parameter func control(f func()) {
fn control(f: impl Fn()) {
from __future__ import pr
Implement procedure control which receives one f()
f();
int_function
parameter f, and runs f. } }
def control(f):

Go supports first class functions, higher-order return f()


functions, user-defined function types, function
literals, and closures.

Go
Rust
Python
Kotlin
Scala
Dart
94 Print type of variable import "reflect" #![feature(core_intrinsic print(type(x)) println(x::class. print(x.runtimeTyp
Print the name of the type of x. Explain if it is a s)] simpleName) e);
static type or dynamic type.
fmt.Println(reflect.TypeOf(x))
Alternative implementation: Static type. Not
This prints the dynamic type of x. fn type_of<T>(_: &T) -> &'s
tatic str {
print(x.__class__) really another way to
This may not make sense in all languages.
Alternative implementation: std::intrinsics::type_n do this in Kotlin.

fmt.Printf("%T", x) ame::<T>()

This prints the dynamic type of x.

println!("{}", type_of(&
x));
As of 2020-09 this is a nightly-
only experimental API.
95 Get file size import "os" use std::fs; import os import 'dart:io';
Assign to variable x the length (number of bytes)
of the local file at path. info, err := os.Stat(path)
let x = fs::metadata(pat x = os.path.getsize(path) final x = (await F
if err != nil {
h)?.len(); ile(path).readAsBy
return err
tes()).length;
}
Alternative implementation:
x := info.Size() let x = path.metadata()?.le Alternative
info has type os.FileInfo . n(); implementation:

path has type &std::path::Path var x = File(pat


h).lengthSync();

96 Check string prefix import "strings" let b = s.starts_with(prefi b = s.startswith(prefix) val b = s.startsW val b = s.startsWith var b = s.startsWi
Set boolean b to true if string s starts with prefix x); ith(prefix) (prefix) th(prefix);
prefix, false otherwise. b := strings.HasPrefix(s, prefix)

97 Check string suffix import "strings" let b = s.ends_with(suffi b = s.endswith(suffix) b = s.endsWith(su val b = s.endsWith(su var b = s.endsWith
Set boolean b to true if string s ends with string x); ffix) ffix) (suffix);
suffix, false otherwise. b := strings.HasSuffix(s, suffix)

98 Epoch seconds to date object import "time" extern crate chrono;


import datetime var d = new DateTi
Convert a timestamp ts (number of seconds in use chrono::prelude::*; me.fromMillisecond
epoch-time) to a date with time d. E.g. 0 -> 1970- d := time.Unix(ts, 0) d = datetime.date.fromtim
sSinceEpoch(ts, is
01-01 00:00:00 ts has type int64.
let d = NaiveDateTime::from estamp(ts)
Utc: true);
The second argument is nanoseconds. _timestamp(ts, 0);

99 Format date YYYY-MM-DD import "time" extern crate chrono;


from datetime import date import 'package:in
Assign to the string x the value of the fields (year, use chrono::prelude::*; tl/intl.dart';
month, day) of the date d, in format YYYY-MM- x := d.Format("2006-01-02") d = date(2016, 9, 28)

DD. d has type time.Time Utc::today().format("%Y-%m- x = d.strftime('%Y-%m-% x = DateFormat('YY


%d") d') YY-MM-DD').format
(d);
Alternative implementation: Alternative implementation:
use time::macros::format_de from datetime import date
scription;
d = date.today()

let format = format_descrip x = d.isoformat()


tion!("[year]-[month]-[da
y]");

let x = d.format(&format).e
xpect("Failed to format the
date");
time crate is better maintained.

Go
Rust
Python
Kotlin
Scala
Dart
100 Sort by a comparator import "sort" items.sort_by(c); items.sort(key=c) items.sortWith(c)
Sort elements of array-like collection items,
type ItemCSorter []Item
c is a key function, see the
using a comparator c.
func (s ItemCSorter) Len() int { doc.
return len(s) }

Alternative implementation:
func (s ItemCSorter) Less(i, j int) bool {
return c(s[i], s[j]) }
import functools
func (s ItemCSorter) Swap(i, j int) { items.sort(key=functools.
s[i], s[j] = s[j], s[i] }
cmp_to_key(c))
c is an old-style comparison
func sortItems(items []Item) {

function
sorter := ItemCSorter(items)

sort.Sort(sorter)

}
c has type func(Item, Item) bool.

Alternative implementation:
import "sort"

type ItemsSorter struct {

items []Item

c func(x, y Item) bool


}

func (s ItemsSorter) Len() int {


return len(s.items) }

func (s ItemsSorter) Less(i, j int) bool {


return s.c(s.items[i], s.items[j]) }

func (s ItemsSorter) Swap(i, j int) {


s.items[i], s.items[j] = s.items[j], s.item
s[i] }

func sortItems(items []Item, c func(x, y It


em) bool) {

sorter := ItemsSorter{

items,

c,

sort.Sort(sorter)

}
ItemsSorter contains c, which can be any
comparator decided at runtime.

Alternative implementation:
import "sort"

sort.Slice(items, func(i, j int) bool {

return c(items[i], items[j])

})
Since Go 1.8, a single func parameter is sufficient
to sort a slice.

Go
Rust
Python
Kotlin
Scala
Dart
101 Load from HTTP GET request into a string import "io/ioutil"
extern crate reqwest;
import urllib.request
val s = scala.io.Sour
Make an HTTP request with method GET to URL import "net/http" use reqwest::Client; ce.fromURL(u).getLine
u, then store the body of the response in string s. with urllib.request.urlop
s().mkString("\n")
res, err := http.Get(u)
let client = Client::new();
en(u) as f:

if err != nil {
let s = client.get(u).send s = f.read()

return err
().and_then(|res| res.text
}
())?;
buffer, err := ioutil.ReadAll(res.Body)

res.Body.Close()
Alternative implementation:
if err != nil {
[dependencies]

return err
ureq = "1.0"
}

s := string(buffer) let s = ureq::get(u).call


().into_string()?;
res has type *http.Response.

buffer has type []byte.

Alternative implementation:
It is idiomatic and strongly recommended to check
[dependencies]

errors at each step.


error-chain = "0.12.4"

reqwest = { version = "0.1


1.2", features = ["blockin
g"] }

use error_chain::error_chai
n;

use std::io::Read;

let mut response = reqwes


t::blocking::get(u)?;

let mut s = String::new();

response.read_to_string(&mu
t s)?;
This is a synchronous
(blocking) reqwest call.

The [dependencies] section


goes to cargo.toml. The optional
feature blocking must be
explicit.

Go
Rust
Python
Kotlin
Scala
Dart
102 Load from HTTP GET request into a file import "fmt"
extern crate reqwest;
import urllib
Make an HTTP request with method GET to URL import "io"
use reqwest::Client;

u, then store the body of the response in file filename, headers = urlli
import "net/http" use std::fs::File;
result.txt. Try to save the data as it arrives if b.request.urlretrieve(u,
possible, without having all its content in memory resp, err := http.Get(u)
let client = Client::new();
'result.txt')

at once. if err != nil {


match client.get(&u).send()
return err
{

}
Ok(res) => {

defer resp.Body.Close()
let file = File::cr
if resp.StatusCode != 200 {
eate("result.txt")?;

return fmt.Errorf("Status: %v", res ::std::io::copy(re


p.Status)
s, file)?;

}
},

out, err := os.Create("result.txt")


Err(e) => eprintln!("fa
if err != nil {
iled to send request: {}",
return err
e),

}
};
defer out.Close()

_, err = io.Copy(out, resp.Body)

if err != nil {

return err

}
resp has type *http.Response.

It is idiomatic and strongly recommended to check


errors at each step, except for the calls to Close.
103 Load XML file into struct import "encoding/xml"
import lxml.etree import scala.xml.XML
Read from the file data.xml and write its contents import "io/ioutil"
into the object x.
x = lxml.etree.parse('dat val xml = XML.loadFil
Assume the XML data is suitable for the type of buffer, err := ioutil.ReadFile("data.xml")
a.xml') e("data.xml")
x. if err != nil {
Use "pip install" to get this
return err
third-party library. It's industry
}
standard for python xml.
err = xml.Unmarshal(buffer, &x)

if err != nil {

return err

}
buffer is a []byte.

&x is the address of x.

You must check errors after each step.


104 Save object into XML file import "encoding/xml"

Write the contents of the object x into the file import "io/ioutil"
data.xml.
buffer, err := xml.MarshalIndent(x, "", "
")

if err != nil {

return err

err = ioutil.WriteFile("data.xml", buffer,


0644)
xml.MarshalIndent is more human-readable than
xml.Marshal.

Go
Rust
Python
Kotlin
Scala
Dart
105 Current executable name import "os"
fn get_exec_name() -> Optio import sys
Assign to string s the name of the currently import "path/filepath" n<String> {

executing program (but not its full path). s = sys.argv[0]


std::env::current_exe()

path := os.Args[0]
sys.argv[0] holds the name of
.ok()

s = filepath.Base(path) the currently running script, you


.and_then(|pb| pb.f
The program path is its "0th argument". ile_name().map(|s| s.to_os_ might use __file__, but if called
string()))
from within a module you
.and_then(|s| s.int would then get the module's
o_string().ok())
__file__ attribute.
}

fn main() -> () {

let s = get_exec_name
().unwrap();

println!("{}", s);

Alternative implementation:
let s = std::env::current_e
xe()

.expect("Can't get the


exec path")

.file_name()

.expect("Can't get the


exec name")

.to_string_lossy()

.into_owned();

106 Get program working directory import "os" use std::env; import os
Assign to string dir the path of the working
directory.
dir, err := os.Getwd() let dir = env::current_dir dir = os.getcwd()
(This is not necessarily the folder containing the ().unwrap(); getcwd stands for Get the
executable itself) dir has type PathBuf Current Working Directory
107 Get folder containing current program import "os"
let dir = std::env::current import os
Assign to string dir the path of the folder import "path/filepath" _exe()?

containing the currently running executable.


dir = os.path.dirname(os.
.canonicalize()

(This is not necessarily the working directory, programPath := os.Args[0]


path.abspath(__file__))
.expect("the current ex
though.) absolutePath, err := filepath.Abs(programPa
e should exist")

th)

.parent()

if err != nil {

.expect("the current ex
return err

e should be a file")

.to_string_lossy()

dir := filepath.Dir(absolutePath)
.to_owned();
Rust doesn't represent paths as
Strings, so we need to convert
the Path returned from
Path::parent. This code chooses
to do this lossily, replacing
characters it doesn't recognize
with �

Go
Rust
Python
Kotlin
Scala
Dart
108 Determine if variable name is defined if 'x' in locals():

Print the value of variable x, but only if x has print x


been declared in this program.

variable name must be quoted.


This makes sense in some languages, not all of
them. (Null values are not the point, rather the Alternative implementation:
very existence of the variable.)
try:

except NameError:

print("does not exis


t")

109 Number of bytes of a type import "reflect" let n = ::std::mem::size_o import pympler.asizeof
Set n to the number of bytes of a variable t (of f::<T>();
type T). var t T
n = pympler.asizeof.asize
tType := reflect.TypeOf(t)
n is "the offset in bytes between of(t)
n := tType.Size() successive elements in an array
`pip install pympler` to get this
with item type T"
This run-time reflection works on a value of the third-party library.
type T.
`sys.getsizeof` is built-in, but
Note that the size does not include the memory has many common failure
indirectly taken by the reference fields: Strings, modes.
slices, etc.

Warning: for a given program, the size of a type is


not the same on a 32-bit machine or a 64-bit
machine.
110 Check if string is blank import "strings" let blank = s.trim().is_emp blank = s is None or s.st val blank = s.isN val blank = Option final blank = s ==
Set the boolean blank to true if the string s is ty(); rip() == '' ullOrBlank() (s).forall(_.trim.isE null || s.trim() =
empty, or null, or contains only whitespace ; false blank := strings.TrimSpace(s) == "" mpty) = '';
otherwise. Trim s, then check if empty.
Use strip (Java 11)
instead of trim for Alternative
Unicode-awareness, or implementation:
more simply use isBlank bool blank = s?.tr
(Java 11)
im()?.isEmpty ?? t
rue;
Option(s) ensures that ? -> null safe check
null is handled. ?? -> on null

Go
Rust
Python
Kotlin
Scala
Dart
111 Launch other program import "os/exec" use std::process::Command; import subprocess
From current process, run program x with
command-line parameters "a", "b". err := exec.Command("x", "a", "b").Run() let output = Command::new subprocess.call(['x',
x's output is ignored.
("x")
'a', 'b'])
To access it, see (*Cmd).Output, .args(&["a", "b"])

(*Cmd).StdoutPipe, etc. .spawn()

.expect("failed to exec
ute process");
spawn() executes x as a child
process without waiting for it to
complete

Alternative implementation:
use std::process::Command;

let output = Command::new


("x")

.args(&["a", "b"])

.output()

.expect("failed to
execute process");
output() waits for x to complete
and collects its output

Alternative implementation:
use std::process::Command;

let output = Command::new


("x")

.args(&["a", "b"])

.status()

.expect("failed to
execute process");
status() waits for x to complete
and collects its exit status
112 Iterate over map entries, ordered by keys import "fmt"
for (k, x) in mymap {
for k in sorted(mymap):
import scala.collecti
Print each key k with its value x from an import "sort" println!("({}, {})", k, print(mymap[k])
on.immutable.SortedMa
associative array mymap, in ascending order of x);
p
keys := make([]string, 0, len(mymap))
dictionaries iterate over their
k. }
for k := range mymap {
keys by default SortedMap.from(myma
keys = append(keys, k)
This assumes mymap is a p).foreach{ case (k,
}
BTreeMap as it is sorted by the x) => println(s"$k =>
sort.Strings(keys)
keys. $x") }

for _, k := range keys {

x := mymap[k]

fmt.Println("Key =", k, ", Value


=", x)

}
First extract the keys, then sort them, then iterate.

Adapt for key types other than string.


113 Iterate over map entries, ordered by values import "fmt"
use itertools::Itertools; for x, k in sorted((x, k)
Print each key k with its value x from an
Go for (k, x) in
Rust
mymap.iter(). for k,x in mymap.items

Python
Kotlin
Scala
Dart
associative array mymap, in ascending order of import "sort" sorted_by_key(|x| x.1) {
()):

x.
println!("[{},{}]", print(k, x)

Note that multiple entries may exist for the same type entry struct {

k, x);

value x. key string


Alternative implementation:
}
value int

import operator
}
Requires the itertools crate
for key, value in sorted
Alternative implementation:
type entries []entry
(d.items(), key=operator.
func (list entries) Len() int { return len let mut items: Vec<_> = mym itemgetter(1)):

(list) }
ap.iter().collect();
print(key, value)
func (list entries) Less(i, j int) bool { r items.sort_by_key(|item| it
operator.itemgetter(1) gets the
eturn list[i].value < list[j].value }
em.1);

second item in the tuple


func (list entries) Swap(i, j int) { list for (k, x) in items {

returned by d.items()
[i], list[j] = list[j], list[i] }
println!("[{},{}]", k,
x);

entries := make(entries, 0, len(mymap))


}
for k, x := range mymap {

entries = append(entries, entry{ke


y: k, values: x})

sort.Sort(entries)

for _, e := range entries {

fmt.Println("Key =", e.key, ", Valu


e =", e.value)

}
Define custom types entry and entries.

Then create a flat list of entries, and sort it.

Alternative implementation:
import "fmt"

import "sort"

type entry struct {

key string

value int

entries := make([]entry, 0, len(mymap))

for k, x := range mymap {

entries = append(entries, entry{ke


y: k, value: x})

sort.Slice(entries, func(i, j int) bool {

return entries[i].value < entries


[j].value

})

for _, e := range entries {

fmt.Println("Key =", e.key, ", Valu


e =", e.value)

}

Go
Rust
Python
Kotlin
Scala
Dart
Using sort.Slice incurs slightly less boilerplate than
sort.Sort.
114 Test deep equality import "reflect" let b = x == y; b = x == y case class A(a: Int,
Set boolean b to true if objects x and y contain b: Float, c: String)

b := reflect.DeepEqual(x, y) The == operator can only be The classes of x and y need to


the same values, recursively comparing all val x = A(1,2.2f,"hel
used by having a type delegate to any contained
referenced elements in x and y.
This uses run-time reflection.
lo")

implement PartialEq. objects' _eq__ implementation.

Tell if the code correctly handles recursive types. DeepEqual correctly handles recursive types. val y = A(1,2.2f,"hel
All objects in the standard
library do so. lo")

b = x == y

115 Compare dates import "time" extern crate chrono;


import datetime
Set boolean b to true if date d1 is strictly before use chrono::prelude::*;
date d2 ; false otherwise. b := d1.Before(d2) b = d1 < d2
d1, d2 have type time.Time. let b = d1 < d2; d1, d2 have type date
116 Remove occurrences of word from string import "strings" s2 = s1.replace(w, ""); s2 = s1.replace(w, '')
Remove all occurrences of string w from string
s1, and store the result in s2. s2 := strings.Replace(s1, w, "", -1)

Alternative implementation:
Replaces w with empty string. -1 means "replace
let s2 = str::replace(s1,
all occurrences".
w, "");
Alternative implementation:
import "strings"

s2 := strings.ReplaceAll(s1, w, "")

117 Get list size n := len(x) let n = x.len();


n = len(x) val n = x.size val n = x.size int n = x.length;
Set n to the number of elements of the list x.
x is a slice or an array.
Alternative implementation:
n = len(x)

118 List to set y := make(map[T]struct{}, len(x))


use std::collections::HashS y = set(x) val y = x.toSet var y = x.toSet();
Create set y from list x.
for _, v := range x {
et;
The default List<T> has a method
x may contain duplicates. y is unordered and has y[v] = struct{}{}

let y: HashSet<_> = x.into_ implementation of Set is to convert directly to


no repeated values. }
iter().collect(); a HashSet Set<T>.
Iterate to add each item to the map.

T is the type of the items.


119 Deduplicate list y := make(map[T]struct{}, len(x))
x.sort();
x = list(set(x)) x = x.toSet().toL x = x.distinct x = x.toSet().toLi
Remove duplicates from the list x.
for _, v := range x {
x.dedup(); ist() st();
Doesn't preserve order
Explain if the original order is preserved. y[v] = struct{}{}
Deduplication in place. Original original ordering is
}
order not maintained. Works Alternative implementation: not preserved
x2 := make([]T, 0, len(y))
O(n*log(n)) from collections import O
for _, v := range x {
rderedDict Alternative
if _, ok := y[v]; ok {
Alternative implementation: implementation:
x2 = append(x2, v) x = list(OrderedDict(zip
use itertools::Itertools; x = x.distinct()
delete(y, v)
(x, x)))
let dedup: Vec<_> = x.iter Ordering is
}
Preserves order
().unique().collect(); preserved
}

x = x2
Original order is preserved.

T is the type of the items.

Iterate twice, from list to map, then from map to list.


Go
Rust
Python
Kotlin
Scala
Dart

This is O(n).

Alternative implementation:
seen := make(map[T]bool)

j := 0

for _, v := range x {

if !seen[v] {

x[j] = v

j++

seen[v] = true

x = x[:j]
The order is preserved.

Use this if T is not a pointer type or reference type.

This is O(n).

Alternative implementation:
seen := make(map[T]bool)

j := 0

for _, v := range x {

if !seen[v] {

x[j] = v

j++

seen[v] = true

for i := j; i < len(x); i++ {

x[i] = nil

x = x[:j]
Order is preserved.

Use this if T is a pointer type or reference type.

Discarded slots are set to nil, to avoid a memory


leak.

This is O(n).
120 Read integer from stdin import "fmt" fn get_input() -> String {
n = int(input("Input Prom
Read an integer value from the standard input let mut buffer = Strin pting String: "))
into the variable n _, err := fmt.Scan(&n)
g::new();

Warning: if the input has a leading 0, it will be std::io::stdin().read_l


interpreted as octal! ine(&mut buffer).expect("Fa
iled");

Alternative implementation:
buffer

import "fmt"
}

_, err := fmt.Scanf("%d", &n)


let n = get_input().trim().
parse::<i64>().unwrap();

Go
Rust
Python
Kotlin
Scala
Dart
Change i64 to what you expect
to get. Do not use unwrap() if
you're not sure it will be parsed
correctly.

Alternative implementation:
use std::io;

let mut input = String::new


();

io::stdin().read_line(&mut
input).unwrap();

let n: i32 = input.trim().p


arse().unwrap();

Alternative implementation:
use std::io::BufRead;

let n: i32 = std::io::stdin


()

.lock()

.lines()

.next()

.expect("stdin should b
e available")

.expect("couldn't read
from stdin")

.trim()

.parse()

.expect("input was not


an integer");

Alternative implementation:
#[macro_use] extern crate t
ext_io;

let n: i32 = read!();

Can also parse several values


and types and delimiters with
scan!()

Also see Rust RFC #3183



Go
Rust
Python
Kotlin
Scala
Dart
121 UDP listen and read import (
use std::net::UdpSocket; import socket
Listen UDP traffic on port p and read 1024 bytes "fmt"

into buffer b. let mut b = [0 as u8; 102 sock = socket.socket(sock


"net"

4];
et.AF_INET, socket.SOCK_D
"os"

let sock = UdpSocket::bind GRAM)

)
(("localhost", p)).unwrap sock.bind((UDP_IP, p))

ServerAddr,err := net.ResolveUDPAddr("udp", ();


while True:

p)
sock.recv_from(&mut b).unwr data, addr = sock.rec
if err != nil {
ap(); vfrom(1024)

return err
print("received messa
}
ge:", data)
ServerConn, err := net.ListenUDP("udp", Ser Buffer size is 1024 bytes
verAddr)

if err != nil {

return err

defer ServerConn.Close()

n,addr,err := ServerConn.ReadFromUDP(b[:102
4])

if err != nil {

return err

if n<1024 {

return fmt.Errorf("Only %d bytes co


uld be read.", n)

122 Declare enumeration type Suit int


enum Suit {
class Suit:
enum Suit {

Create an enumerated type Suit with 4 possible Spades,


SPADES, HEARTS, D SPADES,

values SPADES, HEARTS, DIAMONDS, const (


Hearts,
IAMONDS, CLUBS = range(4) HEARTS,

CLUBS. Spades Suit = iota


Diamonds,
DIAMONDS,

Fake enum, works with any


Hearts
Clubs,
version of python. CLUBS,

Diamonds
} }
Clubs
Alternative implementation:
) from enum import Enum
Go doesn't have enumerations.

class Suit(Enum):

The 4 constants have values 0, 1, 2, 3.


SPADES = 1

HEARTS = 2

DIAMONDS = 3

CLUBS = 4
New in Python 3.4

Go
Rust
Python
Kotlin
Scala
Dart
123 Assert condition if !isConsistent() {
assert!(is_consistent); assert isConsistent assert(isConsisten
Verify that predicate isConsistent returns true, panic("State consistency violated")
t)
raises AssertionError
otherwise report assertion violation.
} Exception.
Needs to be executed
Explain if the assertion is executed even in
Go doesn't provide assertions.
with "--enable-asserts"
production environment or not.
But it's still possible to crash when desired. Running Python with option _- flag with dart and
O or with PYTHONOPTIMZE
dart2js commands.

environment variable In Flutter it will


suppresses all asserts. execute only in debug
mode.

dartdevc
(development
compiler) will execute
it by default.

Go
Rust
Python
Kotlin
Scala
Dart
124 Binary search for a value in sorted array func binarySearch(a []T, x T) int {
a.binary_search(&x).unwrap_ import bisect def binarySearch(a
Write the function binarySearch which returns imin, imax := 0, len(a)-1
or(-1); r, el)

the index of an element having the value x in the def binarySearch(a, x):

for imin <= imax {


This only works if a is an array of res = ar.bsearch
sorted array a, or -1 if no such element exists. i = bisect.bisect_lef
imid := imin + (imax-imin) signed integers.
{|x| x == el}

t(a, x)

/ 2
Generally, a Result or Option res ? res : -1

return i if i != len
switch {
would be more useful. end
(a) and a[i] == x else -1

case a[imid] == x:
return imid

case a[imid] < x:

imin = imid + 1

default:

imax = imid - 1

return -1

}
Iterative algorithm.

It does not always return the smallest possible


index.

You may implement this for any element type T that


is ordered.

Alternative implementation:
import "sort"

func binarySearch(a []int, x int) int {

i := sort.SearchInts(a, x)
if i < len(a) && a[i] == x {

return i

return -1

}
If the elements have type int, then use standard
library's sort.SearchInts.

It returns the smallest matching index.

Alternative implementation:
import "sort"

func binarySearch(a []T, x T) int {

f := func(i int) bool { return a[i]


>= x }

i := sort.Search(len(a), f)

if i < len(a) && a[i] == x {

return i

return -1

}
This uses the standard library generic-purpose
sort.Search. Read the documentation carefully.

It returns the smallest matching index.



Go
Rust
Python
Kotlin
Scala
Dart
125 Measure function call duration import "time" use std::time::{Duration, I import time
measure the duration t, in nanoseconds, of a call nstant};
to the function foo. Print this duration. t1 := time.Now()
t1 = time.perf_counter_ns
foo()
let start = Instant::now();
()

t := time.Since(t1)
foo();
foo()

ns := int64(t / time.Nanosecond)
let duration = start.elapse t2 = time.perf_counter_ns
fmt.Printf("%dns\n", ns) d();
()

t1 has type time.Time.


println!("{}", duration);
print('Nanoseconds:', t2
t has type time.Duration. - t1)
t1 and t2 are int
Alternative implementation:
import "time"

t1 := time.Now()

foo()

t := time.Since(t1)

ns := t.Nanoseconds()

fmt.Printf("%dns\n", ns)
t1 has type time.Time.

t has type time.Duration.

ns has type int64.


126 Multiple return values func foo() (string, bool) {
fn foo() -> (String, bool) def foo():
fun foo() : Pair< def foo(): (String, B
Write a function foo that returns a string and a return "Too good to be", true
{
return 'string', True
String, Boolean> oolean) = ("bar", tru
boolean value. } (String::from("bar"), t = Pair(5, true)
e)
rue)

} fun useFoo() {

val a, b = foo
()

127 Source code inclusion fn main() {


import imp
Import the source code for the function foo body include!("foobody.tx
from a file "foobody.txt" . The declaration must foo = imp.load_module('fo
t");

not reside in the external file. obody', 'foobody.txt').fo


}

o
"foobody.txt" must contain a
To remove all side-effects: del
single Rust expression. If you
sys.modules['foobody']
need several, enclose them in
braces.

Go
Rust
Python
Kotlin
Scala
Dart
128 Breadth-first traversing of a tree func (root *Tree) Bfs(f func(*Tree)) {
use std::collections::VecDe def BFS(f, root):

Call a function f on every node of a tree, in if root == nil {


que; Q = [root]

breadth-first prefix order return


while Q:

struct Tree<V> {

}
n = Q.pop
children: Vec<Tree<V>>,

queue := []*Tree{root}
(0)

value: V

for len(queue) > 0 {


f(n)

t := queue[0]
for child
queue = queue[1:]
in n:

impl<V> Tree<V> {

f(t)
i
fn bfs(&self, f: impl F
queue = append(queue, t.Chi f not n.discovered:

n(&V)) {

ldren...)

let mut q = VecDequ
}
n.discovered = True

e::new();

}
q.push_back(self);

Bfs is a method of type *Tree, and takes function f Q.append(n)


as an argument.
while let Some(t) =
q.pop_front() {

The queue grows and shrinks during traversal, (f)(&t.value);

until all nodes have been visited. for child in &


t.children {

q.push_back
(child);

129 Breadth-first traversing in a graph func (start *Vertex) Bfs(f func(*Vertex)) {


use std::rc::{Rc, Weak};
from collections import d
Call the function f on every vertex accessible queue := []*Vertex{start}
use std::cell::RefCell; eque
from the vertex start, in breadth-first prefix order seen := map[*Vertex]bool{start: tru
def breadth_first(start,
e}

f):

for len(queue) > 0 {

seen = set()

v := queue[0]

q = deque([start])

queue = queue[1:]

while q:

f(v)

vertex = q.popleft()

for next, isEdge := range


f(vertex)

v.Neighbours {

seen.add(vertex)

if isEdge && !seen


q.extend(v for v in v
[next] {

ertex.adjacent if v not i
queue = app
n seen)
end(queue, next)

seen[next] It's best to not recurse in


= true
Python when the structure size
}
is unknown, since we have a
}
fixed, small stack size.
}

}
Bfs is a method of type *Vertex : the receiver is the
start node.

The function f is a parameter of the traversal


method.

Go
Rust
Python
Kotlin
Scala
Dart
struct Vertex<V> {

value: V,

neighbours: Vec<Wea
k<RefCell<Vertex<V>>>>,

// ...

fn bft(start: Rc<RefCell<Ve
rtex<V>>>, f: impl Fn(&V))
{

let mut q = vec![st


art];

let mut i = 0;

while i < q.len() {

let v = Rc::clo
ne(&q[i]);

i += 1;

(f)(&v.borrow
().value);

for n in &v.bor
row().neighbours {

let n = n.u
pgrade().expect("Invalid ne
ighbour");

if q.iter
().all(|v| v.as_ptr() != n.
as_ptr()) {

q.push
(n);

}
See demo for full example.

Go
Rust
Python
Kotlin
Scala
Dart
130 Depth-first traversing in a graph func (v *Vertex) Dfs(f func(*Vertex), seen use std::rc::{Rc, Weak};
def depth_first(start,
Call th function f on every vertex accessible from map[*Vertex]bool) {
use std::cell::RefCell; f):

the vertex v, in depth-first prefix order seen[v] = true


seen = set()

struct Vertex<V> {

f(v)
stack = [start]

value: V,

for next, isEdge := range v.Neighbo while stack:

neighbours: Vec<Wea
urs {
vertex = stack.pop()

k<RefCell<Vertex<V>>>>,

if isEdge && !seen[next] {


f(vertex)

next.Dfs(f, seen)
seen.add(vertex)

}
stack.extend(

// ...

}
v for v in vertex.a
} djacent if v not in seen

fn dft_helper(start: Rc<Ref
Dfs is a method of type *Vertex : the receiver is the )
Cell<Vertex<V>>>, f: &impl
start node.
Fn(&V), s: &mut Vec<*const It's best to not recurse in
The function f is a parameter of the traversal Vertex<V>>) {
Python when the structure size
method.
s.push(start.as_ptr is unknown, since we have a
Start with an empty map as initial seen parameter. ());
fixed, small stack size.
(f)(&start.borrow
().value);

for n in &start.bor
row().neighbours {

let n = n.u
pgrade().expect("Invalid ne
ighbor");

if s.iter
().all(|&p| p != n.as_ptr
()) {

Sel
f::dft_helper(n, f, s);

}
See demo for full example.

Go
Rust
Python
Kotlin
Scala
Dart
131 Successive conditions switch {
if c1 { f1() } else if c2 { f1 if c1 else f2 if c2 el when {
true match {
if (c1) {

Execute f1 if condition c1 is true, or else f2 if case c1:


f2() } else if c3 { f3() } se f3 if c3 else None c1 -> f1()
case _ if c1 => f1 f1;

condition c2 is true, or else f3 if condition c3 is f1()


c2 -> f2()
()
} else if (c2) {

Using if and else


true. case c2:
Alternative implementation: c3 -> f3()
case _ if c2 => f2 f2;

Don't evaluate a condition when a previous f2()


Alternative implementation: } ()
} else if (c3) {

if c1:

condition was true. case c3:


case _ if c3 => f3 f3;

match true {
f1()

f3()
_ if c1 => f1(),
elif c2:
()
}
} _ if c2 => f2(),
f2()
}
_ if c3 => f3(),
elif c3:
Using match with guards
_ => (),
f3()
} Alternative
implementation:
Using match and guards
if (c1) {

f1()

} else if (c2) {

f2()

} else if (c3) {

f3()

Using if and else


132 Measure duration of procedure execution import "time" use std::time::Instant; import timeit
Run procedure f, and return the duration of the
execution of f. func clock(f func()) time.Duration {
let start = Instant::now();
duration = timeit.timeit
t := time.Now()
f();
("f()", setup="from __mai
f()
let duration = start.elapse n__ import f")
return time.Since(t)
d(); Setup makes the function f
} duration is a std::time::Duration, accessible to timeit. Returned
You may use this clock function to time any piece which can be converted into is the execution time in
of code, by wrapping the code in a closure of type seconds with as_secs() seconds
func().
Alternative implementation:
import time

start = time.time()

f()

end = time.time()

return end - start


This returns the duration in
seconds.

Go
Rust
Python
Kotlin
Scala
Dart
133 Case-insensitive string contains import "strings" extern crate regex;
ok = word.lower() in s.lo
Set boolean ok to true if string word is contained use regex::Regex; wer()
in string s as a substring, even if the case doesn't lowerS, lowerWord := strings.ToLower(s), st
match, or to false otherwise. rings.ToLower(word)
let re = Regex::new(&forma
ok := strings.Contains(lowerS, lowerWord) t!("(?i){}", regex::escape

Package strings has no case-insensitive version of (word))).unwrap();

Contains, so we have to convert to lowercase (or let ok = re.is_match(&s);


uppercase) first.
Alternative implementation:
extern crate regex;

use regex::RegexBuilder;

let re =

RegexBuilder::new(&rege
x::escape(word))

.case_insensitive(true)

.build().unwrap();

let ok = re.is_match(s);

Alternative implementation:
let ok = s.to_ascii_lowerca
se().contains(&word.to_asci
i_lowercase());

134 Create a new list items := []T{a, b, c} let items = vec![a, b, c]; items = [a, b, c] val items = listO val items = List(a, var items = [a, b,
Declare and initialize a new list items, containing f(a, b, c) b, c) c];
This creates a slice of type T.
3 elements a, b, c.

Go
Rust
Python
Kotlin
Scala
Dart
135 Remove item from list, by its value for i, y := range items {
if let Some(i) = items.firs items.remove(x) items.remove(x);

Remove at most 1 item from list items, having if y == x {


t(&x) {
Raises a ValueError if x is not
value x. items = append(items[:i], i items.remove(i);
found.
This will alter the original list or return a new list, tems[i+1:]...)
}
depending on which is more idiomatic.
break

If there are several occurrences of x in items, }

remove only one of them. If x is absent, keep }


items unchanged.
First find a matching index i. Then remove at
position i.

Warning: you may have a memory leak at the last


element of the original list, if the items have a
pointer type.

Alternative implementation:
for i, y := range items {

if y == x {

copy(items[i:], items[i+
1:])

items[len(items)-1] = nil

items = items[:len(items)-
1]

break

}
First find a matching index i. Then remove at
position i.

This code is for pointer value type, and has no


memory leak.

Go
Rust
Python
Kotlin
Scala
Dart
136 Remove all occurrences of a value from a list items2 := make([]T, 0, len(items)) items = items.into_iter().f newlist = [item for item items.filter(_ != x) items.removeWhere
Remove all occurrences of value x from list for _, v := range items {
ilter(|&item| item != x).co in items if item != x] ((y)=>y==x);
This will return a new list
items.
if v != x {
llect(); with all the occurrences
This will alter the original list or return a new list, items2 = append(items2, v)
This creates a new list. of x removed.

depending on which is more idiomatic. }

} Alternative implementation: The order of the elements


This is simple and runs in linear time.
items.retain(|&item| item ! is preserved.
However, it allocates memory for the new slice = x);
items2.
items has type Vec.

T is the type of the elements.


retain operates in place.
Alternative implementation:
j := 0

for i, v := range items {

if v != x {

items[j] = items[i]

j++

items = items[:j]
This filters items in-place in linear time.

But don't use it with pointer elements, because you


would have a memory leak at the end of the
underlying array.

Alternative implementation:
j := 0

for i, v := range items {

if v != x {

items[j] = items[i]

j++

for k := j; k < len(items); k++ {

items[k] = nil

items = items[:j]
This filters items in-place in linear time.

The "tail" elements are set to nil to leverage


garbage collection, avoiding a memory leak.

Go
Rust
Python
Kotlin
Scala
Dart
137 Check if string contains only digits b := true
let chars_are_numeric: Vec< b = s.isdigit()
val regex = Regex def onlyDigits(s: Str final b = RegExp
Set the boolean b to true if the string s contains for _, c := range s {
bool> = s.chars()
("[0-9]*")
ing) = s.forall(_.isD (r'^[0-9]+$').hasM
Here digits are characters
only characters in the range '0'..'9', false if c < '0' || c > '9' {
val b = regex.mat igit) atch(s);
having Numeric_Type=Digit or
otherwise. b = false
.map(|c|c.is_numeric())
ches(s)
Numeric_Type=Decimal, this
break
is not exactly the range '0'..'9'.

}
.collect();
Returns false if s is empty. Alternative
} let b = !chars_are_numeric. implementation:
c has type rune. contains(&false); fun String?.isOnl
Note that is_numeric is not just yDigits() = !thi
Alternative implementation: 0 -> 9. s.isNullOrEmpty()
import "strings" See documentation for more && this.all { Cha
info. racter.isDigit(i
isNotDigit := func(c rune) bool { return c
t) }
< '0' || c > '9' }
Alternative implementation:
b := strings.IndexFunc(s, isNotDigit) == -1 We can check all
let b = s.chars().all(cha characters by
r::is_numeric); string's all method,
without any regexp
Alternative implementation:
let b = s.bytes().all(|c|
c.is_ascii_digit());
only return true for ASCII digits
138 Create temp file import "io/ioutil" use tempdir::TempDir;
import tempfile
Create a new temporary file on the filesystem. use std::fs::File;
tmpfile, err := ioutil.TempFile("", "") file = tempfile.Temporary
tmpfile has type *os.File.
let temp_dir = TempDir::new File()
("prefix")?;

Use tmpfile.Name() if you need the path string.


let temp_file = File::open
(temp_dir.path().join("file
Consider defer os.Remove(tmpfile.Name()) for _name"))?;
cleanup. TempDir deletes the directory
and its contents when it is
dropped.
139 Create temp directory import "io/ioutil" extern crate tempdir;
import tempfile
Create a new temporary folder on filesystem, for use tempdir::TempDir;
writing. dir, err := ioutil.TempDir("", "") td = tempfile.TemporaryDi
dir is a string.
let tmp = TempDir::new("pre rectory()
fix")?; tempfile.TemporaryDirectory()
Consider defer os.RemoveAll(dir) for cleanup. was added in Python 3.2 .

It wraps lower-level function


mkdtemp() .

Go
Rust
Python
Kotlin
Scala
Dart
140 Delete map entry delete(m, k) use std::collections::HashM m.pop(k, None) m - k Map myMap = {};

Delete from map m the entry having key k.


ap; myMap.remove(key)
delete is a built-in function.
A missing key will leave the The map m is not
m.remove(&k); map unchanged.
mutated, and a new map Removes from
Explain what happens if k is not an existing key
It's safe even if k is already absent from m. is returned instead. If k
in m. Returns the value at the key if
If the second parameter is doesn't exist in m, no
the key was previously in the
omitted, a missing key will error occurs. The default
map, and 'None' otherwise.
raise the exception KeyError implementation of Map is
a HashMap.

Alternative
implementation:
m -= k
This mutates the map m,
removing k from it. If k
doesn't exist in m, no
error occurs. Only
available on mutable
Map. The default
implementation of Map is
a HashMap.
141 Iterate in sequence over two lists for _, v := range items1 {
for i in item1.iter().chain for x in items1 + items2:

Iterate in sequence over the elements of the list fmt.Println(v)


(item2.iter()) {
print(x)

items1 then items2. For each iteration print the }


print!("{} ", i);

element. for _, v := range items2 {


}
fmt.Println(v)

}
No magic sugar. Write 2 loops.
142 Hexadecimal digits of an integer import "strconv" let s = format!("{:X}", x); s = hex(x)
Assign to string s the hexadecimal representation
s := strconv.FormatInt(x, 16) {:X} produces uppercase hex.

(base 16) of integer x.

{:x} produces lowercase hex.

E.g. 999 -> "3e7" Alternative implementation:


import "fmt"

import "math/big"

s := fmt.Sprintf("%x", x)
x has type *big.Int.

This works because *big.Int implements the


fmt.Formatter interface.

%x is the "verb" for base 16. Not to be confused


with the variable name x.

Go
Rust
Python
Kotlin
Scala
Dart
143 Iterate alternatively over two lists for i := 0; i < len(items1) || i < len(item extern crate itertools; for pair in zip(item1, it
Iterate alternatively over the elements of the list s2); i++ {
em2): print(pair)
items1 and items2. For each iteration, print the for pair in izip!(&items1,
if i < len(items1) {
This will print former
element.
&items2) {

fmt.Println(items1[i])

println!("{}", pair.0);
min(len(item1), item(2)) pairs if
}

Explain what happens if items1 and items2 have println!("{}", pair.1);


len(item1) != len(item2).
if i < len(items2) {

different size. }
fmt.Println(items2[i])

144 Check if file exists import "os" let b = std::path::Path::ne import os import java.io.Fi
Set boolean b to true if file at path fp exists on w(fp).exists();
le;
filesystem; false otherwise.
_, err := os.Stat(fp)
b = os.path.exists(fp)
b := !os.IsNotExist(err) b = File(fb).exis
Beware that you should never do this and then in There's no specific existence check func in Alternative implementation: ts()
the next instruction assume the result is still valid, standard library, so we have to inspect an error from pathlib import Path
this is a race condition on any multitasking OS. return value.
b = Path(fp).exists()

145 Print log line with datetime import "log" eprintln!("[{}] {}", humant import sys, logging
Print message msg, prepended by current date ime::format_rfc3339_seconds
and time.
log.Println(msg) logging.basicConfig(strea
(std::time::SystemTime::now
This prints to os.Stderr by default, with a datetime m=sys.stdout, level=loggi
()), msg);
Explain what behavior is idiomatic: to stdout or prefix. ng.DEBUG, format="%(ascti
Writes an RFC3339 date to me)-15s %(message)s")

stderr, and what the date format is.


stderr with the message logger = logging.getLogge
r('NAME OF LOGGER')

logger.info(msg)
Default output is stderr.

Date format is ISO 8601.


146 Convert string to floating point number import "strconv" let f = s.parse::<f32>().un import locale f = num.parse(s);
Extract floating point value f from its string wrap();
representation s f, err := strconv.ParseFloat(s, 64) s = u'545,2222'

f has type float64. locale.setlocale(locale.L


Alternative implementation:
C_ALL, 'de')

let f: f32 = s.parse().unwr f = locale.atof(s)


ap();
When working with different
locale decimal and thousand
separators you have to use
locale.atof

Alternative implementation:
f = float(s)

Alternative implementation:
f = float(s)

Go
Rust
Python
Kotlin
Scala
Dart
147 Remove all non-ASCII characters import "regexp" let t = s.replace(|c: char| import re
Create string t from string s, keeping only ASCII !c.is_ascii(), "");
characters re := regexp.MustCompile("[[:^ascii:]]")
t = re.sub('[^\u0000-\u00
t := re.ReplaceAllLiteralString(s, "") 7f]', '', s)
Alternative implementation:

Alternative implementation: let t = s.chars().filter(|c Alternative implementation:


| c.is_ascii()).collect::<S
import (
t = s.encode("ascii", "ig
tring>();
"fmt"
nore").decode()
"strings"

"unicode"

t := strings.Map(func(r rune) rune {

if r > unicode.MaxASCII {

return -1

return r

}, s)

148 Read list of integers from stdin import (


use std::{
list(map(int, input().spl
Read a list of integer numbers from the standard "bufio"
io::{self, Read},
it())
input, until EOF. "os"
str::FromStr,

"strconv"
} Alternative implementation:
)
let mut string = String::ne numbers = [int(x) for x i
var ints []int
w();
n input().split()]
s := bufio.NewScanner(os.Stdin)
io::stdin().read_to_string
s.Split(bufio.ScanWords)
(&mut string)?;

for s.Scan() {
let result = string

i, err := strconv.Atoi(s.Text())
.lines()

if err == nil {
.map(i32::from_str)

ints = append(ints, i)
.collect::<Result<Vec<_
}
>, _>>();
}
result is a Result<Vec<i32>,
if err := s.Err(); err != nil {
ParseIntError>.
return err

149 Rescue the princess


As an exception, this content is not under license
CC BY-SA 3.0 like the rest of this website.
150 Remove trailing slash import "strings" if p.ends_with('/') { p.pop p = p.rstrip("/") p.stripSuffix("/")
Remove last character from string p, if this (); }
p = strings.TrimSuffix(p, "/") If there are several trailing
character is a slash /.
p has type String slashes, rstrip will remove all
of them

Go
Rust
Python
Kotlin
Scala
Dart
151 Remove string trailing path separator import "fmt"
let p = if ::std::path::is_ import os
Remove last character from string p, if this import "os"
separator(p.chars().last().
character is the file path separator of current if p.endswith(os.sep):

import "strings" unwrap()) {

platform.
p = p[:-1]
&p[0..p.len()-1]

sep := fmt.Sprintf("%c", os.PathSeparator)

} else {

Note that this also transforms unix root path "/" p = strings.TrimSuffix(p, sep)
p

into the empty string! os.PathSeparator is a rune, it must be converted };


to string.
Alternative implementation:
Alternative implementation:
p = p.strip_suffix(std::pat
import "fmt"

h::is_separator).unwrap_or
import "path/filepath"

(p);
import "strings"

sep := fmt.Sprintf("%c", filepath.Separato


r)

p = strings.TrimSuffix(p, sep)
filepath.Separator is a rune, it must be converted
to string.
152 Turn a character into a string import "fmt" let s = c.to_string(); s = c val s: String =
Create string s containing only the character c. c.toString()
s := fmt.Sprintf("%c", c) a character is a single
character string, not a distinct c has type Char.
datataype
153 Concatenate string with integer import "fmt" let t = format!("{}{}", s, t = '{}{}'.format(s,i) val t = s + i
Create string t as the concatenation of string s i);
and integer i. t := fmt.Sprintf("%s%d", s, i)
Alternative implementation:

Alternative implementation: t = f'{s}{i}'

import "strconv" the 'f' in front of the string


makes it a Literal String, in
t := s + strconv.Itoa(i)
which you can put expressions
This is faster than fmt.Sprintf. inside brackets

Go
Rust
Python
Kotlin
Scala
Dart
154 Halfway between two hex color codes import "fmt"
use std::str::FromStr;
r1, g1, b1 = [int(c1[p:p+
Find color c, the average between colors c1, c2.
import "strconv" use std::fmt; 2], 16) for p in range(1,
6,2)]

c, c1, c2 are strings of hex color codes: 7 chars, r1, _ := strconv.ParseInt(c1[1:3], 16, 0)
"Too long for text box, see
r2, g2, b2 = [int(c2[p:p+
beginning with a number sign # .
r2, _ := strconv.ParseInt(c2[1:3], 16, 0)
online demo"
2], 16) for p in range(1,
Assume linear computations, ignore gamma r := (r1 + r2) / 2

6,2)]

corrections. c = '#{:02x}{:02x}{:02
g1, _ := strconv.ParseInt(c1[3:5], 16, 0)

x}'.format((r1+r2) // 2,
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)

(g1+g2) //2, (b1+b2)// 2)


g := (g1 + g2) / 2

Alternative implementation:
b1, _ := strconv.ParseInt(c1[5:7], 16, 0)

b2, _ := strconv.ParseInt(c2[5:7], 16, 0)


import numpy
b := (b1 + b2) / 2
class RGB(numpy.ndarray):

@classmethod

c := fmt.Sprintf("#%02X%02X%02X", r, g, b) def from_str(cls, rgbst


For conciseness this assumes that input validity r):

has already been checked, so we omit some return numpy.array([

returned errors. int(rgbstr[i:i+2],


16)

Alternative implementation: for i in range(1, l


import "fmt"
en(rgbstr), 2)

import "strconv" ]).view(cls)

var buf [7]byte

def __str__(self):

buf[0] = '#'

self = self.astype(nu
for i := 0; i < 3; i++ {

mpy.uint8)

sub1 := c1[1+2*i : 3+2*i]

return '#' + ''.join


sub2 := c2[1+2*i : 3+2*i]

(format(n, 'x') for n in


v1, _ := strconv.ParseInt(sub1, 16,
self)

0)

v2, _ := strconv.ParseInt(sub2, 16,


c1 = RGB.from_str('#a1b1c
0)

1')

v := (v1 + v2) / 2

print(c1)

sub := fmt.Sprintf("%02X", v)

c2 = RGB.from_str('#1A1B1
copy(buf[1+2*i:3+2*i], sub)

C')

print(c2)

c := string(buf[:])
Loops over each component r, g, b.
print((c1 + c2) / 2)
numpy is standard for array
For conciseness this assumes that input validity
numerics, and works nicely for
has already been checked, so we omit some
this problem. We can represent
returned errors.
a RGB value as a special
numpy array.
155 Delete file import "os" use std::fs; import pathlib
Delete from filesystem the file having path
filepath. err := os.Remove(filepath) let r = fs::remove_file(fil path = pathlib.Path(_file
epath); path)

r has type io::Result<()> path.unlink()



Go
Rust
Python
Kotlin
Scala
Dart
156 Format integer with zero-padding import "fmt" let s = format!("{:03}", s = format(i, '03d')
Assign to string s the value of integer i in 3 i);
decimal digits. Pad with zeros if i < 100. Keep all s := fmt.Sprintf("%03d", i)
digits if i ≥ 1000. Flag 0 means "pad with zeroes, not with spaces".

Flag 3 is the width.


157 Declare constant string const planet = "Earth" const PLANET: &str = "Eart PLANET = 'Earth' val planet = "Ear const String _plan
Initialize a constant planet with string value h"; th" et = "Earth";
Type string is inferred. Names of constants are by
"Earth".
convention written in
uppercase
158 Random sublist import "math/rand" use rand::prelude::*; import random
Create a new list y from randomly picking exactly
k elements from list x.
y := make([]T, k)
let mut rng = &mut rand::th y = random.sample(x, k)
perm := rand.Perm(len(x))
read_rng();
The original ordering is not
It is assumed that x has at least k elements. for i, v := range perm[:k] {
let y = x.choose_multiple(& preserved.
Each element must have same probability to be y[i] = x[v]
mut rng, k).cloned().collec
picked.
} t::<Vec<_>>();
Each element from x must be picked at most Allocate a slice of T of size exactly k.
choose_multiple returns an
once.
perm is a slice of int of size len(x).
Iterator.
Explain if the original ordering is preserved or This is O(len(x)) in space and runtime.

not.
The original ordering is not preserved.
159 Trie type Trie struct {
struct Trie {
class Trie:

Define a Trie data structure, where entries have c rune


val: String,
def __init__(self, pre
an associated value.
children map[rune]*Trie
nodes: Vec<Trie>
fix, value=None):

(Not all nodes are entries) isEntry bool


} self.prefix = pref
value V
ix

} self.children = []

Using type rune, multi-byte characters are correctly self.value = value


handled.

V is the type of the associated values.


160 Detect if 32-bit or 64-bit architecture import "strconv" match std::mem::size_of::<& import sys
Execute f32() if platform is 32-bit, or f64() if char>() {

platform is 64-bit.
if strconv.IntSize==32 {
if sys.maxsize > 2**32:

4 => f32(),

This can be either a compile-time condition f32()


f64()

8 => f64(),

(depending on target) or a runtime detection. }


else:

_ => {}

if strconv.IntSize==64 {
f32()

}
f64()

} Performed at run time.


runtime check

Go
Rust
Python
Kotlin
Scala
Dart
161 Multiply all the elements of a list for i := range elements {
let elements = elements.int elements = [c * x for x i elements.map(_ * c) elements = [for (v
Multiply all the elements of the list elements by a elements[i] *= c
o_iter().map(|x| c * x).col n elements] ar e in elements)
constant c } lect::<Vec<_>>(); e * c];
This maps the lambda function
It is idiomatic to write this explicit loop. that multiplies a number by c to From Dart 2.3, using
Alternative implementation: the list elements , and collection for
elements.iter_mut().for_eac overwrites the old list
h(|x| *x *= c); Alternative
implementation:
It is possible to multiply the
elements of the vector in-place, elements = element
assuming you own the vector, or s.map((e) => e *
that you have mutably borrowed c).toList();
it.
162 Execute procedures depending on options import "flag" if let Some(arg) = ::std::e import sys
execute bat if b is a program option and fox if f is nv::args().nth(1) {

a program option. var b = flag.Bool("b", false, "Do bat")


if 'b' in sys.argv[1:]: b
if &arg == "f" {

var f = flag.Bool("f", false, "Do fox")


at()

fox();

if 'f' in sys.argv[1:]: f
} else if &arg = "b" {

func main() {
ox()

bat();

flag.Parse()

} else {

if *b {
Alternative implementation:
eprintln!("invalid
bar()
options = {

argument: {}", arg),

}
'b': bat

if *f {
'f': fox

} else {

fox()
}

eprintln!("missing argu
}

ment");

} for option, function in o


}
It is idiomatic to use package flag, and pass ptions:

options as -b -f
Alternative implementation: if option in sys.
(with a dash). argv[1:]:

if let Some(arg) = ::std::e


function
nv::args().nth(1) {

()
match arg.as_str() {

"f" => fox(),

"b" => box(),

_ => eprintln!("inv
alid argument: {}", arg),

};

} else {

eprintln!("missing argu
ment");

}

Go
Rust
Python
Kotlin
Scala
Dart
163 Print list elements by group of 2 import "fmt" for pair in list.chunks(2) for x in zip(list[::2], l for (pair <- list.gro
Print all the list elements, two by two, assuming {
ist[1::2]):
uped(2))

list length is even. for i := 0; i+1 < len(list); i += 2 {

println!("({}, {})", pa print(x) println(s"(${pair


fmt.Println(list[i], list[i+1])

ir[0], pair[1]);
original list is called list (0)}, ${pair(1)})")
}
}
Alternative implementation:
from itertools import tee

def pairwise(iterable):

"s -> (s0,s1), (s1,s


2), (s2, s3), ..."

a, b = tee(iterable)

next(b, None)

return zip(a, b)

for a, b in pairwise(lis
t):

print(a, b)
Official documentation
suggestion. Works for any
iterable
164 Open URL in the default browser import "github.com/skratchdot/open-golang/o use webbrowser; import webbrowser
Open the URL s in the default browser.
pen"
Set boolean b to indicate whether the operation webbrowser::open(s).expect webbrowser.open(s)
was successful. b := open.Start(s) == nil ("failed to open URL");
b is not available

Alternative implementation:
func openbrowser(url string) {

var err error

switch runtime.GOOS {

case "linux":

err = exec.Command("xdg-ope
n", url).Start()

case "windows":

err = exec.Command("rundll3
2", "url.dll,FileProtocolHandler", url).Sta
rt()

case "darwin":

err = exec.Command("open",
url).Start()

default:

err = fmt.Errorf("unsupport
ed platform")

if err != nil {

log.Fatal(err)

}

Go
Rust
Python
Kotlin
Scala
Dart
165 Last element of list x := items[len(items)-1] let x = items[items.len()- x = items[-1] var x = items.las val x = items.last x = items.last;
Assign to variable x the last element of list items. 1]; t()
items is a slice.

There is no shortcut, use len!

Panics if the list is empty. Alternative implementation:


let x = items.last().unwrap
();
last() returns an Option<&T>
166 Concatenate two lists ab := append(a, b...) let ab = [a, b].concat(); ab = a + b val ab = a + b val ab = a ++ b var a = [1,2,3];

Create list ab containing all the elements of list a, var b = [3,2,4];

Warning! a and ab may or may not share the same


followed by all elements of list b. Alternative var ab = a + b;
underlying memory.
implementation: Lines 1 and 2 are just
Alternative implementation: val ab = a ::: b initializing the a and b
var ab []T
::: is specific to List.
variables.

ab = append(append(ab, a...), b...)


This ensures that ab is a new list (not sharing any Both a and b must be of On line 3 we initialize
memory with a and b).
type List.
ab with the result of
T is the type of the elements. concatenating a and b
::: is more efficient than together with the +
Alternative implementation: ++ when concatenating operator.
ab := make([]T, len(a)+len(b))
more than 2 lists.
copy(ab, a)

copy(ab[len(a):], b)

167 Trim prefix import "strings" let t = s.trim_start_matche t = s[s.startswith(p) and


Create string t consisting of string s with its prefix s(p); len(p):]
p removed (if s starts with p). t := strings.TrimPrefix(s, p)
Warning: this would remove
several leading occurrences of Alternative implementation:
p, if present.
t = s.removeprefix(p)
See strip_prefix to remove only removeprefix is in Python
one occurrence. 3.9+

Alternative implementation:
let t = if s.starts_with(p)
{ &s[p.len()..] } else { s
};

Alternative implementation:
let t = s.strip_prefix(p).u
nwrap_or(s);
Removes p at most once.

Go
Rust
Python
Kotlin
Scala
Dart
168 Trim suffix import "strings" let t = s.trim_end_matches t = s.removesuffix(w)
Create string t consisting of string s with its suffix (w);
t := strings.TrimSuffix(s, w) removesuffix is in Python 3.9+
w removed (if s ends with w).
This may remove several
occurrences of w at the end of s.

Alternative implementation:
let t = s.strip_suffix(w).u
nwrap_or(s);
Removes at most 1 occurrence
of w
169 String length import "unicode/utf8" let n = s.chars().count(); n = len(s) val n = s.length val n = s.length() int n = s.length;
Assign to integer n the number of characters of
n := utf8.RuneCountInString(s) This is kind of roundabout If s is a Python 3 str, len(s)
string s.

because the default len method returns the number of


Make sure that multibyte characters are properly This assumes that s is encoded in UTF-8 (which is
gives bytes, not characters. characters. If s is a Python 3
handled.
idiomatic in Go).
bytes, len(s) returns the
n can be different from the number of bytes of s.
number of bytes.
170 Get map size n := len(mymap) let n = mymap.len(); n = len(mymap) val n = mymap.size
Set n to the number of elements stored in
mymap.

This is not always equal to the map capacity.


171 Add an element at the end of a list s = append(s, x) s.push(x); s.append(x) s.add(x);
Append element x to the list s.
172 Insert an entry in a map m[k] = v use std::collection::HashMa m[k] = v m[k] = v;
Insert value v for key k in map m. p;
If m[k] already exists, then it is overwritten. If m[k] already exists, then it is
m.insert(k, v); overwritten.

173 Format a number with grouped thousands import "golang.org/x/text/language"


use separator::Separatable; f'{1000:,}' "%,d".format(n)
Number will be formatted with a comma import "golang.org/x/text/message"
separator between every group of thousands. println!("{}", 1000.separat
Alternative implementation:
p := message.NewPrinter(language.English)
ed_string());
s := p.Sprintf("%d\n", 1000) format(1000, ',')
Requires the separator crate

Alternative implementation: Alternative implementation:


import "github.com/floscodes/golang-thousan '{:,}'.format(1000)
ds"

import "strconv"

n := strconv.Itoa(23489)

s := thousands.Separate(n, "en")

This uses a third-pary package golang-thousands



Go
Rust
Python
Kotlin
Scala
Dart
174 Make HTTP POST request import "net/http" [dependencies]
from urllib import reques import 'package:ht
Make a HTTP request with method POST to URL error-chain = "0.12.4"
t, parse tp/http.dart';
u response, err := http.Post(u, contentType,
reqwest = { version = "0.1
body) data = parse.urlencode(<y await post(u, bod
1.2", features = ["blockin
contentType is a string.
our data dict>).encode()
y: body, headers:
g"] }

body is a io.Reader which can be nil. req = request.Request(u, headers);


data=data, method="POST")

use error_chain::error_chai
Alternative implementation: resp = request.urlopen(re
n;

import "net/http"
q)
use std::io::Read;
import "net/url" Explicit use of the "method"
let client = reqwest::block parameter, because "GET" is
response, err := http.PostForm(u, formValue ing::Client::new();
used when "data" is None
s) let mut response = client.p
formValues has type net/url.Values ost(u).body("abc").send()?;
This is a synchronous
(blocking) reqwest call.

The [dependencies] section


goes to cargo.toml. The optional
feature blocking must be
explicit.

response has type


Result<Response>.
175 Bytes to hex string import "encoding/hex" use hex::ToHex; s = a.hex()
From array a of n bytes, build the equivalent hex
string s of 2n digits.
s := hex.EncodeToString(a) let mut s = String::with_ca
Each byte (256 possible values) is encoded as This is faster than fmt.Sprintf pacity(2 * a.len());

two hexadecimal characters (16 possible values a.write_hex(&mut s).expect


per digit). Alternative implementation: ("Failed to write");
import "fmt"
Alternative implementation:
s := fmt.Sprintf("%x", a)
use core::fmt::Write;
%x base 16, lower-case, two characters per byte.

let mut s = String::with_ca


This is slower than hex.EncodeToString pacity(2 * n);

for byte in a {

write!(s, "{:02X}", byt


e)?;

176 Hex string to byte array import "encoding/hex" use hex::FromHex; a = bytearray.fromhex(s)
From hex string s of 2n digits, build the
equivalent array a of n bytes.
a, err := hex.DecodeString(s)
let a: Vec<u8> = Vec::from_
Each pair of hexadecimal characters (16 possible if err != nil {
hex(s).expect("Invalid Hex
values per digit) is decoded into one byte (256 log.Fatal(err)
String");
possible values). }

177 Find files with a given list of filename import "path/filepath"


import os
extensions import "strings"
Construct a list L that contains all filenames that
have the extension ".jpg" , ".jpeg" or ".png" in
directory D and all it's subdirectories.
L := []string{}

Go
Rust
Python
Kotlin
Scala
Dart
err := filepath.Walk(D, func(path string, i extensions = [".jpg", ".j
nfo os.FileInfo, err error) error {
peg", ".png"]

if err != nil {
L = [f for f in os.listdi
fmt.Printf("failure accessi r(D) if os.path.splitext
ng a path %q: %v\n", path, err)
(f)[1] in extensions]

return err

Doesn't look in subdirectories


}

because I didn't read the


for _, ext := range []string{".jp
question properly.
g", ".jpeg", ".png"} {

if strings.HasSuffix(path, Alternative implementation:


ext) {

import re

L = append(L, path)

import os
break

}
filtered_files = ["{}/
}
{}".format(dirpath, filen
return nil
ame) for dirpath, _, file
}) names in os.walk(D) for f
ilename in filenames if r
e.match(r'^.*\.(?:jpg|jpe
g|png)$', filename)]
* list comprehension

* iterate over all files and all


directories in tree under D (os
module)

* iterate over all files found

* filter with regex matching the


end of the filename (re module)

* regex is cached, but may be


compiled beforehands

Alternative implementation:
import glob

import itertools

list(itertools.chain(*(gl
ob.glob("*/**.%s" % ext)
for ext in ["jpg", "jpe
g", "png"])))

Alternative implementation:
glob

os

extensions = [".jpg", ".j


peg", ".png"]

L = [f for f in glob.glob
(os.path.join(D, "**/*"),
recursive=True)) if os.pa
th.splitext(f)[1] in exte
nsions]

Go
Rust
Python
Kotlin
Scala
Dart
178 Check if point is inside rectangle import "image" struct Rect {
b = (x1 < x < x2) and (y1
Set boolean b to true if if the point with x1: i32,
< y < y2)
coordinates (x,y) is inside the rectangle with p := image.Pt(x, y)

x2: i32,
Edges NOT considered to be
coordinates (x1,y1,x2,y2) , or to false otherwise.
r := image.Rect(x1, y1, x2, y2)
y1: i32,
inside.
Describe if the edges are considered to be inside b := p.In(r) y2: i32,

the rectangle. Points on the edge of the rectangle are considered }

as in the rectangle.
impl Rect {

fn contains(&self, x: i
32, y: i32) -> bool {

return self.x1 < x


&& x < self.x2 && self.y1 <
y && y < self.y2;

179 Get center of a rectangle import "image" struct Rectangle {


center = ((x1+x2)/2, (y1+ fun center(x1: in
Return the center c of the rectangle with x1: f64,
y2)/2) t, y1: int, x2: i
coördinates(x1,y1,x2,y2) c := image.Pt((x1+x2)/2, (y1+y2)/2)
y1: f64,
center is a tuple that can be nt, y2: int) = Pa
Implementation for x1, x2, y1 and y2 as int. x2: f64,
ir((x1 + x2)/2,
accessed using index 0 for x
y2: f64,
and 1 for y. (y1 + y2)/2)

e.g. center[0] Alternative


impl Rectangle {
implementation:
pub fn center(&self) -> Alternative implementation: data class Point
(f64, f64) {
from collections import n (val x: Double, v
((self.x1 + sel amedtuple al y: Double)

f.x2) / 2.0, (self.y1 + sel data class Rectan


f.y2) / 2.0)
Point = namedtuple('Poin
gle(val x1: Doubl
}
t', 'x y')

e, val y1: Doubl


} center = Point((x1+x2)/2,
e, val x2: Doubl
(y1+y2)/2)
e, val y2: Doubl
center is a namedtuple, that e){

can be accessed either using x fun center() =


and y or an index (0,1)
Point( x = (x1 +
x2)/2, y =(y1 + y
e.g. center.x or center[0] 2)/2)

180 List files in directory import "io/ioutil" use std::fs; import os


Create list x containing the contents of directory
d.
x, err := ioutil.ReadDir(d) let x = fs::read_dir(d).unw x = os.listdir(d)
x is a slice of os.FileInfo rap();
x may contain files and subfolders.
x is a fs::ReadDir iterator over
No recursive subfolder listing. std::io::Result<fs::DirEntry>

Alternative implementation:
let x = std::fs::read_dir
(d)?.collect::<Result<Vec<_
>, _>()?;

Go
Rust
Python
Kotlin
Scala
Dart
182 Quine program package main
fn main() {
s = 's = %r\nprint(s%%s)'
object Quine extends
Output the source of the program. let x = "fn main() {\n print(s%s) App {

import "fmt"
let x = ";
val s =

let y = "print!(\"{} """object Quine e


func main() {
{:?};\n let y = {:?};\n xtends App {

fmt.Printf("%s%c%s%c\n", s, 0x60, {}\", x, x, y, y)\n}\n";


| val s =

s, 0x60)
print!("{}{:?};
| ""%2$s%1
}
let y = {:?};
$s%2$s""

{}", x, x, y, y)
| print(s.stri
var s = `package main
} pMargin.format(s,
"\""))

import "fmt"
Alternative implementation: |}"""

fn main(){print!("{}, print(s.stripMargi
func main() {
{0:?})}}","fn main(){print! n.format(s, "\""))

fmt.Printf("%s%c%s%c\n", s, 0x60, (\"{},{0:?})}}\"")} }


s, 0x60)

var s = `

183 Make HTTP PUT request import "net/http" import requests


Make a HTTP request with method PUT to URL
u req, err := http.NewRequest("PUT", u, body)
content_type = 'text/plai
if err != nil {
n'

return err
headers = {'Content-Typ
}
e': content_type}

req.Header.Set("Content-Type", contentType)
data = {}

req.ContentLength = contentLength

response, err := http.DefaultClient.Do(req) r = requests.put(u, heade


This assumes you know contentLength rs=headers, data=data)

beforehand.
status_code, content = r.
body is a io.Reader which can be nil. status_code, r.content

184 Tomorrow import "time" let t = chrono::Utc::now(). from datetime import dat var now = new Date
Assign to variable t a string representing the day, date().succ().to_string(); e, timedelta Time.now();

month and year of the day after the current date. t := time.Now().Add(24 * time.Hour).Format var t = now.add(ne
("2006-01-02") t = str(date.today() + ti
w Duration(days:
medelta(days=1))
1));

Go
Rust
Python
Kotlin
Scala
Dart
185 Execute function in 30 seconds import "time" use std::time::Duration;
import threading
Schedule the execution of f(42) in 30 seconds. use std::thread::sleep;
timer := time.AfterFunc(
timer = threading.Timer(3
30*time.Second,
sleep(Duration::new(30, 0.0, f, args=(42,) )

func() {
0));
timer.start()

f(42)
f(42);

})
f is wrapped in an anonymous func having 0 arg
and 0 return value.

The timer instance can be used to cancel the call.

Alternative implementation:
import "time"

go func() {

time.Sleep(30 * time.Second)

f(42)

}()
The code after the goroutine launch executes
immediately.

Consider adding proper synchronization where


needed. Data races are forbidden!
186 Exit program cleanly import "os" use std::process::exit; import sys import kotlin.sys sys.exit(0)
Exit a program cleanly indicating no error to OS tem.exitProcess
os.Exit(0) exit(0); sys.exit(0)
Since exit() ultimately “only” exitProcess(0)
Alternative implementation: raises an exception, it will only
import "os" exit the process when called
from the main thread, and the
defer os.Exit(0)
exception is not intercepted.
defer would be used in order to run subsequent
deferred statements before exiting

Go
Rust
Python
Kotlin
Scala
Dart
187 Disjoint Set class UnionFind:

Disjoint Sets hold elements that are partitioned def __init__(self, si


into a number of disjoint (non-overlapping) sets. ze):

self.rank = [0] *
size

self.p = [i for i
in range(size)]

def find_set(self,
i):

if self.p[i] ==
i:

return i

else:

self.p[i] = s
elf.find_set(self.p[i])

return self.p
[i]

def is_same_set(self,
i, j):

return self.find_
set(i) == self.find_set
(j)

def union_set(self,
i, j):

if not self.is_sa
me_set(i, j):

x, y = self.f
ind_set(i), self.find_set
(j)

188 Matrix multiplication import "gonum.org/v1/gonum/mat" import numpy as np


Perform matrix multiplication of a real matrix a
with nx rows and ny columns, a real matrix b c := new(mat.Dense)
c = a @ b

with ny rows and nz columns and assign the c.Mul(a, b) Python 3.5 (PEP465)
value to a real matrix c with nx rows and nz introduced the @ operator for
columns. matrix multiplication.

Alternative implementation:
import numpy as np

c = np.matmul(a, b)
You can also use np.matrix
instead of np.array. Be careful
when using array, because the
* operator performs
elementwise multiplication.

Go
Rust
Python
Kotlin
Scala
Dart
189 Filter and transform list var y []Result
let y = x.iter()
y = [T(e) for e in x if P val y = x.collect { c
Produce a new list y containing the result of for _, e := range x {
.filter(P)
(e)] ase e if P(e) => T(e)
function T applied to all elements e of list x that if P(e) {
.map(T)
}
match the predicate P. y = append(y, T(e))
.collect::<Vec<_>> Alternative implementation:
}
(); y = list(map(T, filter(P,
} x)))
No functional style: just a regular loop.

y is not fully allocated upfront because the number


of matching elements is not known yet.
190 Call an external C function // void foo(double *a, int n);
extern "C" {

Declare an external C function with the prototype


// double a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, /// # Safety

9};
///

void foo(double *a, int n);


import "C"
/// `a` must point to a
n array of at least size 10

and call it, passing an array (or a list) of size 10 C.foo(C.a, 10) fn foo(a: *mut libc::c_
to a and 10 to n.
double, n: libc::c_int);

Use only standard features of your language.


let mut a = [0.0, 1.0, 2.0,
3.0, 4.0, 5.0, 6.0, 7.0, 8.
0, 9.0];

let n = 10;

unsafe {

foo(a.as_mut_ptr(), n);

191 Check if any value in a list is larger than a for _, v := range a {


if a.iter().any(|&elem| ele if any(v > x for v in a):

limit if v > x {
m > x) {
f()
Given a one-dimensional array a, check if any f()
f()

value is larger than x, and execute the procedure break


}
f if that is the case }

192 Declare a real variable with at least 20 digits import "math/big" use rust_decimal::Decimal;
import decimal
Declare a real variable a with at least 20 digits; if use std::str::FromStr;
the type does not exist, issue an error at compile a, _, err := big.ParseFloat("123456789.1234 a = decimal.Decimal('1234
time. 56789123465789", 10, 200, big.ToZero) let a = Decimal::from_str 567890.123456789012345')
2nd arg is the base.
("1234567890.12345678901234
3rd arg is the precision.
5").unwrap();
4th arg is the rounding mode.

The precision is the maximum number of mantissa


bits available to represent the value.

Go
Rust
Python
Kotlin
Scala
Dart
193 Transpose a two-dimensional matrix import numpy as np
Declare two two-dimensional arrays a and b of
dimension n*m and m*n, respectively. Assign to a = np.array([[1,2], [3,
b the transpose of a (i.e. the value with index 4], [5,6]])

interchange). b = a.T

Alternative implementation:
a = [[1,2], [3,4], [5,6]]

b = list(map(list, zip(*
a)))

194 Circular shift of a two-dimensional array import numpy as np


Given an array a, set b to an array which has the
values of a along its second dimension shifted by b = np.roll(a, m, axis=1)
n. Elements shifted out should come back at the
other end.
195 Pass a two-dimensional array #[macro_use] extern crate i def foo(a):

Pass an array a of real numbers to the procedure tertools; print(len(a))

(resp. function) foo. Output the size of the array, print(sum(

and the sum of all its elements when each fn foo(a: Vec<Vec<usize>>)
x*(i+1) + y*(i+1)
element is multiplied with the array indices i and j {

*2 for i, (x, y) in enume


(assuming they start from one). println!(

rate(a)

"Length of array:
))
{}",

a.clone()

.into_iter()

.flatten()

.collect::<Vec<
usize>>()

.len()

);

let mut sum = 0;

for (i, j) in izip!(&a


[0], &a[1]) {

sum += i * j

println!("Sum of all pr
oducts of indices: {}", su
m);

}
By useing izip! macro we can
chain itteration over elements of
array a
196 Pass a sub-array fn foo(el: &mut i32) {
def foo(data, r):
fun foo(a : IntAr
Given an integer array a of size n, pass the first, *el = 42;
for i in r: data[i] = ray, idx: IntProg
third, fifth and seventh, ... up to the m th element }
42
ression) =

to a routine foo which sets all these elements to a.iter_mut().take(m).step_b return


idx.forEach{ a
42. y(2).for_each(foo); [it] = 42 }

foo(a, range(0, m+1, 2)) foo(a, 0 .. (m-1)


step 2)


Go
Rust
Python
Kotlin
Scala
Dart
197 Get a list of lines from a file import "io/ioutil"
use std::io::prelude::*;
with open(path) as f:
import java.io.Fi
Retrieve the contents of file at path into a list of import "strings" use std::io::BufReader;
lines = f.readlines() le
strings lines, in which each element is a line of use std::fs::File;
the file. func readLines(path string) ([]string, erro val lines = File
r) {
let lines = BufReader::new (path).readLines
b, err := ioutil.ReadFile(path)
(File::open(path).unwrap())
()
if err != nil {
.lines()

return nil, err


.collect::<Vec<_>>
}
();
lines := strings.Split(string(b),
"\n")

return lines, nil

198 Abort program execution with error condition import "os" use std::process; import sys
Abort program execution with error condition x
(where x is an integer value) os.Exit(x) process::exit(x); sys.exit(x)
This does not run any
destructors. Clean up is left to
the OS.
199 Truncate a file at the current file position import "os" F.truncate(F.tell())
Truncate a file F at the given file position.
err := os.Truncate(F, position)

200 Return hypotenuse import "math" fn hypot(x:f64, y:f64)-> f6 import math


Returns the hypotenuse h of the triangle where 4 {

the sides adjacent to the square angle have h := math.Hypot(x, y) h = math.hypot(x, y)


let num = x.powi(2) +
lengths x and y. y.powi(2);

num.powf(0.5)

201 Euclidean norm import numpy as np


Calculate n, the Euclidean norm of data (an
array or list of floating point values). np.linalg.norm(data)

202 Sum of squares import "math" let s = data.iter().map(|x| s = sum(i**2 for i in dat
Calculate the sum of squares s of data, an array x.powi(2)).sum::<f32>(); a)
of floating point values. var s float64

for _, d := range data {

s += math.Pow(d, 2)

203 Calculate mean and standard deviation import "github.com/gonum/stat" import statistics
Calculate the mean m and the standard deviation
s of the list of floating point values data. m, s := stat.MeanStdDev(data, nil) m = statistics.mean(data)

github.com/gonum/stat is a third party package, but sd = statistics.stdev(dat


well established. a)

204 Return fraction and exponent of a real import "math" import math
number
Given a real number a, print the fractional part fmt.Println(math.Frexp(a)) print(math.frexp(a))
and the exponent of the internal representation of
that number. For 3.14, this should print
(approximately)

0.785 2


Go
Rust
Python
Kotlin
Scala
Dart
205 Get an environment variable import "os" use std::env; import os
Read an environment variable with the name
"FOO" and assign it to the string variable foo. If it foo, ok := os.LookupEnv("FOO")
let foo;
try:

does not exist or if the system does not support if !ok {


match env::var("FOO") {
foo = os.environ['FO
environment variables, assign a value of "none". foo = "none"
Ok(val) => foo = val,
O']

} Err(_e) => foo = "non except KeyError:

e".to_string(),
foo = "none"
Alternative implementation: }
import "os" Alternative implementation:
Alternative implementation: from os import getenv
foo := os.Getenv("FOO")

use std::env;
if foo == "" {
foo = getenv('FOO', 'non
foo = "none"
let foo = env::var("FOO").u e')
} nwrap_or("none".to_string
This is fine if empty string means "no value" in your ()); Alternative implementation:
use case.
import os
Alternative implementation:
foo = os.environ.get('FO
To distinguish between an empty value and an use std::env;
O', 'none')
unset value, use os.LookupEnv.
let foo = match env::var("F Python exposes environment
OO") {
variables as an associative
Ok(val) => val,
array(dict), so the standard get
Err(_e) => "none".to_st method can be used.
ring(),

};

Alternative implementation:
use std::env;

if let Ok(tnt_root) = env::


var("TNT_ROOT") {

//

}

Go
Rust
Python
Kotlin
Scala
Dart
206 Switch statement with strings switch str {
match str {
switch = {'foo': foo,

Execute different procedures foo, bar, baz and case "foo":


"foo" => foo(),
'bar': bar,

barfl if the string str contains the name of the foo()


"bar" => bar(),
'baz': baz,

respective procedure. Do it in a way natural to case "bar":


"baz" => baz(),
'barfl': barfl

the language. bar()


"barfl" => barfl(),
}

case "baz":
_ => {}

baz()
}
switch_funct = switch.get
case "barfl":
(string)

barfl()
if switch_funct : switch_
} funct()
Python does not natively
support switch statements, but
we can use a dictionary to
replicate one.

The get() method will return the


value of the given key if it
exists and None otherwise
where foo, bar, baz, and barf1
are all declared functions.

We then can check if the get


method returned a value, and if
it did, execute the returned
function.
207 Allocate a list that is automatically a := make([]T, n) let a = vec![0; n]; def func():

deallocated a = [0] * n

Elements have type T.


Heap allocations are deallocated
Allocate a list a containing n elements (n # local variable auto
a is garbage-collected after the program exits its when the variable goes out of
assumed to be too large for a stack) that is matically deallocated at
scope, unless we let it "escape" by taking its scope.
automatically deallocated when the program exits end of function

reference.

the scope it is declared in. return


The runtime decides if a lives in the stack on in the
heap.
208 Formula with arrays import "math" for i in 0..a.len() {
import math
Given the arrays a,b,c,d of equal length and the a[i] = e * (a[i] +
scalar e, calculate a = e*(a+b*c+cos(d)).
func applyFormula(a, b, c, d []float64, e f for i in xrange(len(a)):

b[i] * c[i] + d[i].cos());

Store the results in a. loat64) {


a[i] = e*(a[i] +
}
for i, v := range a {
b[i] + c[i] + math.cos(a
a[i] = e * (v + b[i] + c[i] Should be sure that all the type [i]))

+ math.Cos(d[i]))
of the variables should be f32 or
}
f64 in order to use the cos() Alternative implementation:
} method.
import math

a = [e*(a[i] + b[i] + c
[i] + math.cos(d[i])) for
i in range(len(a))]

Go
Rust
Python
Kotlin
Scala
Dart
209 Type with automatic deep deallocation type t struct {
struct T {
class T:

Declare a type t which contains a string s and an s string


s: String,
def __init__(self, s,
integer array n with variable size, and allocate a n []int
n: Vec<usize>,
n):

variable v of type t. Allocate v.s and v.n and set }


}
self.s = s

them to the values "Hello, world!" for s and self.n = n

[1,4,9,16,25], respectively. Deallocate v, v := t{


fn main() {
return

automatically deallocating v.s and v.n (no s: "Hello, world!",


let v = T {

memory leaks). n: []int{1, 4, 9, 16, 25}, s: "Hello, v = T('hello world', [1,


} world!".into(),
4, 9, 16, 25])

After v goes out of scope, v and all its fields will be n: vec![1, del v

garbage-collected, recursively 4,9,16,25]

};

}
When a variable goes out of
scope, all member variables are
deallocated recursively.
210 Compiler version and options import "runtime" import sys
Assign, at runtime, the compiler version and the
options the program was compilerd with to version := runtime.Version() version = sys.version

variables version and options, respectively, and options = sys.flags


print them. For interpreted languages, substitute
the version of the interpreter.

Example output:

GCC version 10.0.0 20190914 (experimental)

-mtune=generic -march=x86-64

211 Create folder import "os" use std::fs; import os


Create the folder at path on the filesystem
err := os.Mkdir(path, os.ModeDir) fs::create_dir(path)?; os.mkdir(path)
This works only if path's parent already exists. This doesn't create parent
directories. fs::create_dir_all
Alternative implementation: does.
import "os"
Alternative implementation:
err := os.MkdirAll(path, os.ModeDir)
use std::fs;
MkdirAll creates any necessary parents.
fs::create_dir_all(path)?;
create_dir_all creates
intermediate parent folders as
needed
212 Check if folder exists import "os" use std::path::Path; import os
Set boolean b to true if path exists on the
filesystem and is a directory; false otherwise. info, err := os.Stat(path)
let b: bool = Path::new(pat b = os.path.isdir(path)
b := !os.IsNotExist(err) && info.IsDir() h).is_dir();

Go
Rust
Python
Kotlin
Scala
Dart
213 Case-insensitive string compare use itertools::Itertools; import itertools
Compare four strings in pair-wise variations. The
string comparison can be implemented with an for x in strings
strings = ['ᾲ στο διάολ
equality test or a containment test, must be case- .iter()
ο',

insensitive and must apply Unicode casefolding. .combinations(2)


'ὰι στο διάολ
.filter(|x| x[0].to_low ο',

ercase() == x[1].to_lowerca 'ᾺͅΣΤΟ ΔΙΆΟΛ


se())
Ο',

{
'ᾺΙ ΣΤΟ ΔΙΆΟΛ
println!("{:?} == Ο']

{:?}", x[0], x[1])

} for a, b in itertools.com
binations(strings, 2):

print(a, b, a.casefol
d() == b.casefold())

214 Pad string on the right import "strings"


s = s.ljust(m, c)
Append extra character c at the end of string s to import "utf8"
make sure its length is at least m.

The length is the number of characters, not the if n := utf8.RuneCountInString(s); n < m {

number of bytes. s += strings.Repeat(c, m-n)

}
c here is a one-character string

Go
Rust
Python
Kotlin
Scala
Dart
215 Pad string on the left import "strings"
use unicode_width::{Unicode s = s.rjust(m, c)
Prepend extra character c at the beginning of import "utf8" WidthChar, UnicodeWidthSt
string s to make sure its length is at least m.
r};
The length is the number of characters, not the if n := utf8.RuneCountInString(s); n < m {

number of bytes. s = strings.Repeat(c, m-n) + s


if let Some(columns_short)
} = m.checked_sub(s.width())
c here is a one-character string {

let padding_width = c

.width()

.filter(|n| *n > 0)

.expect("padding ch
aracter should be visibl
e");

// Saturate the columns


_short

let padding_needed = co
lumns_short + padding_width
- 1 / padding_width;

let mut t = String::wit


h_capacity(s.len() + paddin
g_needed);

t.extend((0..padding_ne
eded).map(|_| c)

t.push_str(&s);

s = t;

}
This uses the Unicode display
width to determine the padding
needed. This will be appropriate
for most uses of monospaced
text.

It assumes that m won't combine


with other characters to form a
grapheme.
216 Pad a string on both sides s = s.center(m, c)
Add extra character c at the beginning and
ending of string s to make sure its length is at
least m.

After the padding the original content of s should


be at the center of the result.

The length is the number of characters, not the


number of bytes.

E.g. with s="abcd", m=10 and c="X" the result


should be "XXXabcdXXX".

Go
Rust
Python
Kotlin
Scala
Dart
217 Create a Zip archive import "archive/zip"
use zip::write::FileOption import zipfile
Create a zip-file with filename name and add the import "bytes"
s;
files listed in list to that zip-file. with zipfile.ZipFile(nam
import "os"

let path = std::path::Pat e, 'w', zipfile.ZIP_DEFLA


import "io"

h::new(_name);
TED) as zip:

import "io/ioutil"
let file = std::fs::File::c for file in list_:

buf := new(bytes.Buffer)
reate(&path).unwrap();
zip.write(file)
w := zip.NewWriter(buf)
let mut zip = zip::ZipWrite Files listed in list_
for _, filename := range list {
r::new(file); zip.start_fil
input, err := os.Open(filename)
e("readme.txt", FileOption
if err != nil {
s::default())?;

return err
zip.write_all(b"Hello, Worl
}
d!\n")?;

output, err := w.Create(filename)


zip.finish()?;
if err != nil {
zip.finish() returns a Result.
return err

}
Alternative implementation:
_, err = io.Copy(output, input)
use zip::write::FileOption
if err != nil {
s;
return err

}
fn zip(_name: &str, _list:
}
Vec<&str>) -> zip::result::
ZipResult<()>

err := w.Close()
{

if err != nil {
let path = std::path::P
return err
ath::new(_name);

}
let file = std::fs::Fil
e::create(&path).unwrap();

err = ioutil.WriteFile(name, buf.Bytes(), 0 let mut zip = zip::ZipW


777)
riter::new(file);

if err != nil {
for i in _list.iter() {

return err
zip.start_file(i as
} &str, FileOptions::default
())?;

list contains filenames of files existing in the


}

filesystem.

zip.finish()?;

In this example, the zip data is buffered in memory


Ok(())

before writing to the filesystem.


}
Note: This function does not
write any contents to the files.

Go
Rust
Python
Kotlin
Scala
Dart
218 List intersection seta := make(map[T]bool, len(a))
use std::collections::HashS c = list(set(a) & set(b))
Create the list c containing all unique elements for _, x := range a {
et;
that are contained in both lists a and b.
seta[x] = true
Alternative implementation:
c should not contain any duplicates, even if a and let unique_a = a.iter().col
}
c = list(set(a).intersect
b do.
lect::<HashSet<_>>();

setb := make(map[T]bool, len(a))


ion(b))
The order of c doesn't matter. let unique_b = b.iter().col
for _, y := range b {

lect::<HashSet<_>>();
This avoids converting b into a
setb[y] = true

set prior to the intersection.


}

let c = unique_a.intersecti
on(&unique_b).collect::<Vec
var c []T

<_>>();
for x := range seta {

if setb[x] {

Alternative implementation:
c = append(c, x)

use std::collections::HashS
}

et;
}
Convert to sets, then iterate in one pass.
let set_a: HashSet<_> = a.i
The runtime cost is O(n).
nto_iter().collect();

Elements have type T. let set_b: HashSet<_> = b.i


nto_iter().collect();

let c = set_a.intersection
(&set_b);

219 Replace multiple spaces with single space import "regexp" use regex::Regex; import re
Create string t from the value of string s with
each sequence of spaces replaced by a single whitespaces := regexp.MustCompile(`\s+`)
let re = Regex::new(r"\s t = re.sub(' +', ' ', s)
space.
t := whitespaces.ReplaceAllString(s, " ") +").unwrap();
Only replaces spaces.
The whitespaces regexp can be reused. let t = re.replace_all(s, "
Explain if only the space characters will be ");
replaced, or the other whitespaces as well: tabs, Replaces all whitespaces.
newlines.
220 Create a tuple value t := []interface{}{
let t = (2.5, "hello", -1); t = (2.5, "hello", -1)
Create t consisting of 3 values having different 2.5,
Tuples are like “fixed-length Tuples are immutable.

types.
"hello",
collections of values of different They may be created with
make(chan int),
types”. elements of any type.
Explain if the elements of t are strongly typed or } They are strongly typed.
not.
A slice of empty interface may hold any values (not
strongly typed).

Alternative implementation:
a, b, c := 2.5, "hello", make(chan int)
a, b, c are strongly typed and could hold the
multiple return values of a func.

While a, b, c can most often be used like a tuple,


they are technically not a tuple named t.
221 Remove all non-digits characters import "regexp" let t: String = s.chars().f import re
Create string t from string s, keeping only digit ilter(|c| c.is_digit(10)).c
characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. re := regexp.MustCompile("[^\\d]") t = re.sub(r"\D", "", s)
ollect();
t := re.ReplaceAllLiteralString(s, "")

Go
Rust
Python
Kotlin
Scala
Dart
222 Find the first index of an element in list i := -1
let opt_i = items.iter().po i = items.index(x) if x i i=items.indexOf(x)
Set i to the first index in list items at which the for j, e := range items {
sition(|y| *y == x);
n items else -1
element x can be found, or -1 if items does not if e == x {

contain x. i = j

break
let i = match opt_i {

}
Some(index) => index as
} i32,

There is no generic func for this, consider an None => -1

explicit loop in your own strongly typed helper func. };


The first line is ideomatic Rust
and allows you to work with an
Option.

The rest is some (potentially


useless/ugly) implementation of
"returning -1"

Alternative implementation:
let i = items.iter().positi
on(|y| *y == x).map_or(-1,
|n| n as i32);
Rust uses the usize type to
index lists, but it can't be
negative. We need to manually
convert it to an i32 to be able to
return -1

Go
Rust
Python
Kotlin
Scala
Dart
223 for else loop items := []string{"foo", "bar", "baz", "qu let mut found = false;
items = ['foo', 'bar', 'b items.find { it -
Loop through list items checking a condition. Do x"}
for item in items {
az', 'qux']
> it == "baz" }?.
something else if no matches are found.
if item == &"baz" {
let {

for _, item := range items {


println!("found i for item in items:
println("found
A typical use case is looping through a series of if item == "baz" {
t");
if item == 'baz':
it")

containers looking for one that matches a fmt.Println("found it")


found = true;
print('found it')
} ?: println("nev
condition. If found, an item is inserted; otherwise, goto forelse
break;
break
er found it")
a new container is created.
}
}
else:

}
}
print('never found i Alternative
These are mostly used as an inner nested loop, {
if !found {
t') implementation:
and in a location where refactoring inner logic fmt.Println("never found it")
println!("never found i if(items.any { it
into a separate function reduces clarity. }
t");
Alternative implementation: == "baz" })

forelse: } items = ['foo', 'bar', 'b println("found


Go does not have a for...else construct, but a Rust does not have a for...else az', 'qux']
it")

structured goto label works well. construct, so we use a found else

variable. True if "baz" in items el println("never


se False found it")
Alternative implementation:
This uses python's ternary
if let None = items.iter(). operator: <statement1> if
find(|&&item| item == "rock <condition> else <statement2>.

star programmer") {
The "in" operator is more
println!("NotFoun idiomatic than looping over a
d");
container. However the run-
}; time performance is tied to the
type of collection being iterated
Alternative implementation: over.
items

.iter()

.find(|&&item| item ==
"rockstar programmer")

.or_else(|| {

println!("NotFoun
d");

Some(&"rockstar pro
grammer")

});
find returns the first Some(T)
that satisfies condition, or
returns None. We can use
or_else to do action when None
is returned. If you'd like to do
something with found element,
use and_then.

Go
Rust
Python
Kotlin
Scala
Dart
224 Add element to the beginning of the list items = append([]T{x}, items...) use std::collections::VecDe items = [x] + items
Insert element x at the beginning of list items. que;
items has type []T.

This implementation always allocates a full new Alternative implementation:


items.push_front(x);
slice. items.insert(0, x)

Alternative implementation:
items = append(items, x)

copy(items[1:], items)

items[0] = x
This implementation is verbose, but it will often not
allocate, when items has enough capacity.
225 Declare and use an optional argument func f(x ...int) {
fn f(x: Option<()>) {
def f(x=None):

Declare an optional integer argument x to if len(x) > 0 {


match x {
if x is None:

procedure f, printing out "Present" and its value if println("Present", x[0])


Some(x) => println! print("Not presen
it is present, "Not present" otherwise } else {
("Present {}", x),
t")

println("Not present")
None => println!("N else:

}
ot present"),
print("Present",
} }
x)
Go does not have optional arguments, but to some }
extend, they can be mimicked with a variadic
parameter.

x is a variadic parameter, which must be the last


parameter for the function f.

Strictly speaking, x is a list of integers, which might


have more than one element. These additional
elements are ignored.
226 Delete last element from list items = items[:len(items)-1] items.pop(); items.pop()
Remove the last element from list items.
If items is already empty, this will panic with "slice items is a mutable Vec
bounds out of range".
227 Copy list y := make([]T, len(x))
let y = x.clone(); y = x[:]
Create new list y containing the same elements copy(y, x) The elements type must
as list x.

Elements have type T


implement the trait
Note that the destination is the first argument of std::clone::Clone
Subsequent modifications of y must not affect x
copy.
(except for the contents referenced by the
elements themselves if they contain pointers).
228 Copy a file import "io/ioutil"
use std::fs; import shutil
Copy the file at path src to dst. import "os"
fs::copy(src, dst).unwrap shutil.copy(src, dst)
();

Go
Rust
Python
Kotlin
Scala
Dart
func copy(dst, src string) error {
data, err := ioutil.ReadFile(src)

if err != nil {

return err

stat, err := os.Stat(src)

if err != nil {

return err

return ioutil.WriteFile(dst, data,


stat.Mode())

This is fine if the file is small enough to fit in


memory.

Warning: in Unix, the destination file's mode and


permission bits may be different from the source
file's, because umask is applied.

Alternative implementation:
import "io/ioutil"

import "os"

func copy(dst, src string) error {


data, err := ioutil.ReadFile(src)

if err != nil {

return err

stat, err := os.Stat(src)

if err != nil {

return err

err = ioutil.WriteFile(dst, data, s


tat.Mode())

if err != nil {

return err

return os.Chmod(dst, stat.Mode())

}
This is fine if the file is small enough to fit in
memory.

This preserves the source file's mode and


permission bits (overriding umask in Unix).

Alternative implementation:
import "io"

import "os"

Go
Rust
Python
Kotlin
Scala
Dart
func copy(dst, src string) error {
f, err := os.Open(src)

if err != nil {

return err

defer f.Close()

stat, err := f.Stat()

if err != nil {

return err

g, err := os.OpenFile(dst, os.O_WRO


NLY|os.O_CREATE|os.O_TRUNC, stat.Mode())

if err != nil {

return err

defer g.Close()

_, err = io.Copy(g, f)

if err != nil {

return err

return os.Chmod(dst, stat.Mode())

}
This can handle large files.
229 Cancel an operation import "context"
Interrupt an ongoing processing p.
ctx, cancel := context.WithCancel(context.B
ackground())

go p(ctx)

somethingElse()

cancel()
Pass a Context to p and execute p.

p is responsible for shutting down gracefully when


ctx is canceled
230 Timeout import "context"
Cancel an ongoing processing p if it has not
finished after 5s. ctx, cancel := context.WithTimeout(context.
Background(), 5*time.Second)

defer cancel()

p(ctx)
p is responsible for shutting down gracefully when
ctx is canceled.
231 Test if bytes are a valid UTF-8 string import "unicode/utf8" let b = std::str::from_utf8 try:

Set b to true if the byte sequence s consists (&bytes).is_ok(); s.decode('utf8')

entirely of valid UTF-8 character code points, b := utf8.Valid(s)


b = True

false otherwise. s is a []byte. except UnicodeError:

b = False


Go
Rust
Python
Kotlin
Scala
Dart
232 Read a command line boolean flag import "flag" use clap::{Arg, App}; import argparse
Print "verbose is true" if the flag -v was passed to
the program command line, "verbose is false" var verbose = flag.Bool("v", false, "verbos let matches = App::new("My parser = argparse.Argumen
otherwise. e")
Program")
tParser()

flag.Parse()
.arg(Arg::w parser.add_argument('-v',
fmt.Println("verbose is", *verbose) ith_name("verbose")
action='store_true', dest
verbose has pointer type *bool.
.short ='verbose')

Call Parse only once, after all flags are defined and ("v")
args = parser.parse_args
before flags are read.
.takes_ ()

Flags must be passed before the non-flag value(false))


print('verbose is', args.
arguments. .get_matche verbose)

s();

if matches.is_present("verb
ose") {

println!("verbose is tr
ue")

} else {

println!("verbose is f
alse")

233 Read a command line string flag import "flag" import argparse
Print the value of the flag -country passed to the
program command line, or the default value var country = flag.String("country", "Canad parser = argparse.Argumen
"Canada" if no such flag was passed. a", "user home country")
tParser()

flag.Parse()
parser.add_argument('-cou
fmt.Println("country is", *country) ntry', default='Canada',
country has pointer type *string.
dest='country')

Call Parse only once, after all flags are defined and args = parser.parse_args
before flags are read.
()

Flags must be passed before the non-flag print('country is', args.


arguments. country)

234 Encode bytes to base64 import "encoding/base64" let s = base64::encode(dat import base64
Assign to string s the standard base64 encoding a);
of the byte array data, as specified by RFC 4648. s := base64.StdEncoding.EncodeToString(dat b = base64.b64encode(dat
a) a)

s = b.decode()
b is a bytes object

s is a unicode string

Go
Rust
Python
Kotlin
Scala
Dart
235 Decode base64 import "encoding/base64" let bytes = base64::decode import base64 import java.util.
Assign to byte array data the bytes represented (s).unwrap();
Base64
by the base64 string s, as specified by RFC data, err := base64.StdEncoding.DecodeStrin data = base64.decode(s)
4648. g(s) String(Base64.get
Decoder().decode
(s))
Unfortunately, at the
time of the writing, I
couldn't find kotlin's
decoder that uses
base64 however
ASCII and UTF
decoders are
natively available
236 Large quotient import "math/big" import fractions
Initialize a quotient q = a/b of arbitrary precision.
a and b are large integers. q := new(big.Rat)
q = fractions.Fraction(a,
q.SetString(str) b)
str is a quotient string including numerator, slash,
denominator.

Alternative implementation:
import "math/big"

q := new(big.Rat)

q.SetFrac(a, b)
a, b have type *big.Int

Alternative implementation:
import "math/big"

q := big.NewRat(a, b)
This creates a quotient from int64 values.

Subsequent computations have arbitrary precision.


237 Xor integers c := a ^ b let c = a ^ b; c = a ^ b
Assign to c the result of (a xor b)
a, b, c have the same integer type (signed or
unsigned)

Alternative implementation:
import "math/big"

c := new(big.Int)

c.Xor(a, b)
a, b, c have big integer type *big.Int

Go
Rust
Python
Kotlin
Scala
Dart
238 Xor byte arrays c := make([]byte, len(a))
let c: Vec<_> = a.iter().zi c = bytes([aa ^ bb for a
Write in a new byte array c the xor result of byte for i := range a {
p(b).map(|(x, y)| x ^ y).co a, bb in zip(a, b)])
arrays a and b.
c[i] = a[i] ^ b[i]
llect();
}
a and b have the same size.
Byte slices []byte are more idiomatic than arrays.

Alternative implementation:
var c T

for i := range a {

c[i] = a[i] ^ b[i]

}
T is a fixed-sized array type, e.g. [5]byte.
239 Find first regular expression match import "regexp" use regex::Regex; import re
Assign to string x the first word of string s
consisting of exactly 3 digits, or the empty string re := regexp.MustCompile(`\b\d\d\d\b`)
let re = Regex::new(r"\b\d m = re.search(r'\b\d\d\d
if no such match exists.
x := re.FindString(s) \d\d\b").expect("failed to \b', s)

re may (and should) be reused.


compile regex");
x = m.group(0) if m else
A word containing more digits, or 3 digits as a \b matches word boundaries.
let x = re.find(s).map(|x| ''
substring fragment, must not match. \d matches a single digit. x.as_str()).unwrap_or("");

240 Sort 2 lists together import "sort" let mut tmp: Vec<_> = a.ite import operator
Lists a and b have the same length. Apply the r().zip(b).collect();

same permutation to a and b to have them sorted type sorter struct {


tmp.as_mut_slice().sort_by_
temp = list(zip(a, b))

based on the values of a. k []K


temp.sort(key=operator.it
key(|(&x, _y)| x);

t []T
emgetter(0))

let (aa, bb): (Vec<i32>, Ve


}
a, b = zip(*work)
c<i32>) = tmp.into_iter().u
nzip();

func (s *sorter) Len() int {

return len(s.k)

func (s *sorter) Swap(i, j int) {

s.k[i], s.k[j] = s.k[j], s.k[i]

s.t[i], s.t[j] = s.t[j], s.t[i]

func (s *sorter) Less(i, j int) bool {

return s.k[i] < s.k[j]

sort.Sort(&sorter{

k: a,

t: b,

})
The custom type sorter implements the 3 methods
of sort.Interface.
Swap affects the order of 2 slices at once.

Go
Rust
Python
Kotlin
Scala
Dart
241 Yield priority to other threads import "runtime" ::std::thread::yield_now();

Explicitly decrease the priority of the current busywork();


process, so that other execution threads have a runtime.Gosched()

better chance to execute now. Then resume busywork()


normal execution and call function busywork. After Gosched, the execution of the current
goroutine resumes automatically.
242 Iterate over a set for e := range x {
use std::collections::HashS for e in x:

Call a function f on each element e of a set x. f(e)


et; f(e)
}
for item in &x {

x is implemented as a map whose values are Alternative implementation:


f(item);

ignored. } list(map(lambda e: f(e),


x))
x is a HashSet
It will not work until list
transformation
243 Print list import "fmt" println!("{:?}", a) print(a) print(a);
Print the contents of the list or array a on the
fmt.Println(a) a is a Vec.
Newline automatically
standard output.
Vec<T> doesn't implement the appended.
a is a slice.

Display trait, however it


This works fine for simple types and structs.

implements the Debug trait.


It won't dereference pointers.
244 Print map import "fmt" println!("{:?}", m); print(m)
Print the contents of the map m to the standard
output: keys and values. fmt.Println(m)
This works fine for simple types of keys and values.

It won't dereference pointers.

Alternative implementation:
import "fmt"

fmt.Printf("%q", m)
The verb %q prints strings with nice double-quotes.

It's not the best for all types of keys and values,
though.
245 Print value of custom type import fmt; println!("{:?}", x); print(x)
Print the value of object x having custom type T,
fmt.Println(x) Implement fmt::Debug or
for log or debug.
fmt::Display for T
Will be more relevant if T implements fmt.Stringer
246 Count distinct elements distinct := make(map[T]bool)
use itertools::Itertools; c = len(set(items)) val c = items.dis
Set c to the number of distinct elements in list for _, v := range items {
tinct().size
items. let c = items.iter().unique
distinct[v] = true

().count();
}

c := len(distinct)
This assumes the type T is comparable with ==

Go
Rust
Python
Kotlin
Scala
Dart
247 Filter list in-place j := 0
let mut j = 0;
del_count = 0

Remove all the elements from list x that don't for i, v := range x {
for i in 0..x.len() {
for i in range(len(x)):

satisfy the predicate p, without allocating a new if p(v) {


if p(x[i]) {
if not p(x[i - del_co
list. x[j] = x[i]
x[j] = x[i];
unt]):

Keep all the elements that do satisfy p.


j++
j += 1;
del x[i - del_cou
}
}
nt]

For languages that don't have mutable lists, refer }


}
del_count += 1
to idiom #57 instead. x = x[:j] x.truncate(j); This is O(n^2)
Discarded elements are overwritten.

x is resliced to its new length.


Alternative implementation:
If the elements of x have a pointer type, then you x.retain(p);
should take care of a potential memory leak by The predicate p takes as
setting all x[j:] elements to nil. argument a reference to the
element.
Alternative implementation:
for i, v := range x {

if p(v) {

x[j] = x[i]

j++

for k := j; k < len(x); k++ {

x[k] = nil

x = x[:j]
When elements of x have pointer type, it is
necessary to set discarded slice elements to nil, to
avoid a memory leak.
248 Construct a 64-bit floating-point value import math
Construct the "double precision" (64-bit) floating
point number d from the mantissa m, the sign = -1 if s else 1

exponent e and the sign flag s (true means the d = math.ldexp(sign*m,e)


sign is negative).
249 Declare and assign multiple variables a, b, c := 42, "hello", 5.0 let (a, b, c) = (42, "hell a, b, c = 42, 'hello', 5. val (a, b, c) = l
Define variables a, b and c in a concise way.
o", 5.0); 0 istOf("A", "B",
a, b and c may have different types.
Explain if they need to have the same type. "C")
a, b, and c may have different a, b and c may have different
types. types. This is a
destructuring
declaration

Go
Rust
Python
Kotlin
Scala
Dart
250 Pick a random value from a map import "math/rand" import random
Choose a value x from map m.

m must not be empty. Ignore the keys. func pick(m map[K]V) V {


x = random.choice(list(m.
k := rand.Intn(len(m))
values()))
i := 0

for _, x := range m {

if i == k {

return x

i++

panic("unreachable")

Alternative implementation:
import "math/rand"

func pick(m map[K]V) V {

k := rand.Intn(len(m))

for _, x := range m {

if k == 0 {

return x

k--

panic("unreachable")

251 Parse binary digits import "strconv" let i = i32::from_str_radix i = int(s, 2) var i = int.parse
Extract integer value i from its binary string (s, 2).expect("Not a binary (s, radix: 2);

representation s (in radix 2)


i, err := strconv.ParseInt(s, 2, 0)
number!");
E.g. "1101" -> 13 i has type int64
252 Conditional assignment if condition() {
x = if condition() { "a" } x = "a" if condition() el val x = if(condit
Assign to the variable x the value "a" if calling the x = "a"
else { "b" }; se "b" ion()) "a" else
function condition returns true, or the value "b" } else {
"b"
otherwise. x = "b"

}
No syntactic sugar
253 Print stack trace import "runtime/debug" use backtrace::Backtrace; import inspect
Print the stack frames of the current execution
thread of the program. debug.PrintStack() let bt = Backtrace::new();
for frame in inspect.stac
Prints to standard error println!("{:?}", bt); k():

print(frame)


Go
Rust
Python
Kotlin
Scala
Dart
254 Replace value in list for i, s := range x {
for v in &mut x {
for i, v in enumerate(x):

Replace all occurrences of "foo" with "bar" in the if s == "foo" {


if *v == "foo" {
if v == "foo":

string list x x[i] = "bar"


*v = "bar";
x[i] = "bar"
}
}
Explicit loop is the most
} } readable

Alternative implementation:
x = ["bar" if v=="foo" el
se v for v in x]
List comprehension
255 Print a set use std::collections::HashS print(x)
Print the values of the set x to the standard et;
output.

The order of the elements is irrelevant and is not println!("{:?}", x);


required to remain the same next time.
256 Count backwards import "fmt" (0..=5).rev().for_each(|i| for i in range(5, -1, - for (int i = 5; i
Print the numbers 5, 4, ..., 0 (included), one line println!("{}", i));
1):
>= 0; i--) {

per number. for i := 5; i >= 0; i-- {

Use _(0..=5).rev()_.
print(i) print(i);

fmt.Println(i)

(5..=0) will not do anything. }


}

257 Traverse list backwards import "fmt" for (i, item) in items.iter for i in range(len(items)
Print each index i and value x from the list items, ().enumerate().rev() {
-1, -1, -1):

from the last down to the first. for i := len(items) - 1; i >= 0; i-- {

println!("{} = {}", i, print(i, items[i])


x := items[i]

*item);

fmt.Printf("Item %d = %v \n", i, x)

}
}

258 Convert list of strings to list of integers import "strconv" let b: Vec<i64> = a.iter(). b = [int(elem) for elem i
Convert the string values from list a into a list of map(|x| x.parse::<i64>().un n a]
integers b. b := make([]int, len(a))

wrap()).collect();
var err error

for i, s := range a {
a has type Vec<&str>
b[i], err = strconv.Atoi(s)

Alternative implementation:
if err != nil {

return err
let b: Vec<i32> = a.iter().
}
flat_map(|s| s.parse().ok
} ()).collect();

ok converts a Result to an
Option. flat_map collects all
values of Some.
259 Split on several separators import "regexp" let parts: Vec<_> = s.split import re
Build list parts consisting of substrings of input (&[',', '-', '_'][..]).coll
string s, separated by any of the characters ',' re := regexp.MustCompile("[,\\-_]")
parts = re.split('[,_
ect();
(comma), '-' (dash), '_' (underscore). parts := re.Split(s, -1) \-]', s)
Square brackets mean "match any of these
characters".

The special character dash must be escaped with a


backslash.

The backslash must be escaped with a backslash.



Go
Rust
Python
Kotlin
Scala
Dart
260 Create an empty list of strings var items []string let items: Vec<String> = ve items = [] var items = <Strin
Declare a new list items of string elements, c![]; g>[];
items is nil, which is idiomatic for an empty slice
containing zero elements
Alternative
implementation:
List<String> items
= [];

261 Format time hours-minutes-seconds import "time" use time::macros::format_de import datetime
Assign to string x the value of fields (hours, scription;
minutes, seconds) of date d, in format x := d.Format("15:04:05") d = datetime.datetime.now
HH:MM:SS. let format = format_descrip ()

tion!("[hour]:[minute]:[sec x = d.strftime('%H:%M:%
ond]");
S')
let x = d.format(&format).e
xpect("Failed to format the
time");

262 Count trailing zero bits import "math/bits" let t = n.trailing_zeros(); t = bin(n)[::-1].find
Assign to t the number of trailing 0 bits in the ('1')
binary representation of the integer n.
t := bits.TrailingZeros(n)
Works for n > 0. Integers in
n has type uint
Python have no fixed bitsize,
E.g. for n=112, n is 1110000 is base 2 and the
so t is undefined for n = 0.
result is t=4
263 Integer logarithm in base 2 fn log2d(n: f64) -> f64 {
import math
Write two functions log2d and log2u, which n.log2().floor()

calculate the binary logarithm of their argument n def log2d(n):

rounded down and up, respectively. n is return math.floor(mat


assumed to be positive. Print the result of these h.log2(n))

fn log2u(n: f64) -> f64 {

functions for numbers from 1 to 12. n.log2().ceil()

def log2u(n):

return math.ceil(mat
h.log2(n))

fn main() {

for n in 1..=12 {

for n in range(1, 13):

let f = f64::from
print(n, log2d(n), lo
(n);

g2u(n))
println!("{} {}
{}", n, log2d(f), log2u Functions accept both int and
(f));
float parameters
}

}
Alternatively, you could use n as
f64 instead of f64::from(n), but
that doesn't pass the Clippy
pedantic lint cast_lossless.

Go
Rust
Python
Kotlin
Scala
Dart
264 Automated passing of array bounds fn foo(v: Vec<Vec<i32>>) {
def foo(a):

Pass a two-dimensional integer array a to a println!("{} {}", v.len print(len(a), len(a


procedure foo and print the size of the array in (), v[0].len());
[0]))

each dimension. Do not pass the bounds }


return

manually. Call the procedure with a two-


dimensional array. let v = vec![

vec![1, 2, 3],
a = [[1,2,3], [4,5,6]]

vec![4, 5, 6],
foo(a)

];

foo(v);

Alternative implementation:
fn foo<const X: usize, cons
t Y: usize>(_: [[i32;X];Y])
{

println!("{} {}", Y,
X);

let a = [

[1, 2, 3],

[4, 5, 6],

];

foo(a);

265 Calculate parity of an integer let i = 42i32;


i = 42

Set the integer variable i to 42 and calculate its let p = i.count_ones() % 2; p = bin(i).count('1') % 2
parity (i.e. 0 if it contains an even number of bits,
1 if it contains an odd number of bits).
266 Repeated string import (
let s = v.repeat(n); s = v * n val s = v.repeat var s = v * n;
Assign to the string s the value of the string v "fmt"
(n)
String * num repeats
repeated n times, and write it out.
"strings"
println(s) copies of the string.
)
E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
s := strings.Repeat(v, n)

fmt.Println(s)

Go
Rust
Python
Kotlin
Scala
Dart
267 Pass string to argument that can be of any import "fmt" use std::any::Any; def foo(x):

type if isinstance(x, st
Declare an argument x to a procedure foo that func foo(x interface{}) {
fn foo(x: &dyn Any) {

r):

can be of any type. If the type of the argument is if s, ok := x.(string); ok {


if let Some(s) = x.down
print(x)

a string, print it, otherwise print "Nothing."


fmt.Println(s)
cast_ref::<String>() {

else:

} else {
println!("{}", s);

print('Nothing.')

Test by passing "Hello, world!" and 42 to the fmt.Println("Nothing.")


} else {

return

procedure. }
println!("Nothing")

}
}

foo('Hello, world!')

foo(42)

func main() {

foo("Hello, world!")
fn main() {

foo(42)
foo(&"Hello, world!".to
} _owned());

An argument of type interface{} may receive a foo(&42);

value of any type.


}
We convert it with a type assertion. Dynamic typing isn't idiomatic
Rust.
268 User-defined operator class Vector:

Define a type vector containing three floating def __init__(self, x,


point numbers x, y, and z. Write a user-defined y, z):

operator x that calculates the cross product of self.x = x

two vectors a and b. self.y = y

self.z = z

return

def __mul__(self, oth


er):

return Vector(sel
f.y * other.z - self.z *
other.y,

sel
f.z * other.x - self.x *
other.z,

sel
f.x * other.y - self.y *
other.x)

result = a * b
Python doesn't allow operators
with user-defined names
269 Enum to String let e = t::bike;
e = T.horse
val e = T.BIKE

Given the enumerated type t with 3 possible let s = format!("{:?}", e);


s = e.name
val s = e.name

values: bike, car, horse.


print(s)
println(s)
Set enum e to one of the allowed values of t.
println!("{}", s);
Set string s to hold the string representation of e
This requires the enum to derive
(so, not the ordinal value).

the Debug trait.


Print s.

Go
Rust
Python
Kotlin
Scala
Dart
270 Test for quiet or signaling NaN import math
Given a floating point number r1 classify it as
follows:
if math.isnan(r1):

If it is a signaling NaN, print "This is a signaling print('This is a quie


NaN."
t NaN.')

If it is a quiet NaN, print "This s a quiet NaN."


else:

If it is not a NaN, print "This is a number."


print('This is a numb
er.')

Python makes no effort to


distinguish signaling NaNs
from quiet NaNs, and behavior
for signaling NaNs remains
unspecified. Typical behavior is
to treat all NaNs as though
they were quiet.
271 Test for type extension def tst(x):

If a variable x passed to procedure tst is of type if isinstance(x, fo


foo, print "Same type." If it is of a type that o):

extends foo, print "Extends type." If it is neither, print("Same typ


print "Not related." e.")

elif issubclass(type
(x), foo):

print("Extends ty
pe.")

else:

print("Not relate
d.")

272 Play FizzBuzz for i in range(1,101):

Fizz buzz is a children's counting game, and a if i % 15 == 0:

trivial programming task used to affirm that a print("FizzBuzz")

programmer knows the basics of a language: elif i % 3 == 0:

loops, conditions and I/O.


print("Fizz")

elif i % 5 == 0:

The typical fizz buzz game is to count from 1 to print("Buzz")

100, saying each number in turn. When the else:

number is divisible by 3, instead say "Fizz". print(i)


When the number is divisible by 5, instead say
"Buzz". When the number is divisible by both 3
and 5, say "FizzBuzz"

Go
Rust
Python
Kotlin
Scala
Dart
273 Check if folder is empty import "os" use std::fs; import os
Set the boolean b to true if the directory at
filepath p is empty (i.e. doesn't contain any other dir, err := os.Open(p)
let b = fs::read_dir(p).unw b = os.listdir(p) == []
files and directories) if err != nil {
rap().count() == 0;
panic(err)

defer dir.Close()

_, err = dir.Readdirnames(1)

b := err == io.EOF
Error may happen, and should be dealt with.

b is set to true if EOF was encountered before


reading 1 contained file name.
274 Remove all white space characters import "strings"
import re
Create string t from string s, removing all the import "unicode"
spaces, newlines, tabulations, etc. t = re.sub('\\s', '', s)
t := strings.Map(func(r rune) rune {

if unicode.IsSpace(r) {

return -1

return r

}, s)
In this mapping, -1 means "drop this character"
275 Binary digits to byte array import "strconv" n = (len(s) - 1) // 8 + 1

From the string s consisting of 8n binary digit a = bytearray(n)

characters ('0' or '1'), build the equivalent array a n := len(s) / 8

for i in range(n):

of n bytes.
a := make([]byte, n)

b = int(s[i * 8:(i +
Each chunk of 8 binary digits (2 possible values for i := range a {

1) * 8], 2)

per digit) is decoded into one byte (256 possible b, err := strconv.ParseInt(s[i*8:i*
a[i] = b

values). 8+8], 2, 0)

if err != nil {

log.Fatal(err)

a[i] = byte(b)

}
bytes are unsigned in Go (byte is an alias for
uint8)

Consider handling the error appropriately, in case s


is malformed.
276 Insert an element in a set x[e] = struct{}{} x.add(e)
Insert an element e into the set x.
x has type map[E]struct{}

Alternative implementation:
x[e] = true
x has type map[E]bool

Go
Rust
Python
Kotlin
Scala
Dart
277 Remove an element from a set delete(x, e) x.remove(e)
Remove the element e from the set x.

x has type map[E]struct{}


A KeyError exception is raised
if e was already absent.
Explains what happens if e was already absent
If x is nil or there is no such element, delete is a
from x.
no-op.

Alternative implementation:
delete(x, e)
x has type map[E]bool

If x is nil or there is no such element, delete is a


no-op.
278 Read one line from the standard input import "bufio"
import sys
Read one line into the string line.
import "os"
line = sys.stdin.readline
Explain what happens if EOF is reached. s := bufio.NewScanner(os.Stdin)
()
if ok := s.Scan(); !ok {
In case of EOF an empty string
log.Fatal(s.Err())
is returned.
}

line := s.Text()
This handles any error (including EOF) by aborting
the program execution.

WARNING: this works only for lines smaller than


64kB each.
279 Read list of strings from the standard input import "bufio"
use std::io::prelude::*; import sys
Read all the lines (until EOF) into the list of import "os"
strings lines. let lines = std::io::stdin lines = sys.stdin.readlin
var lines []string
().lock().lines().map(|x| es()
s := bufio.NewScanner(os.Stdin)
x.unwrap()).collect::<Vec<S
for s.Scan() {
tring>>();
line := s.Text()

lines = append(lines, line)

if err := s.Err(); err != nil {

log.Fatal(err)

}
WARNING: this works only for lines smaller than
64kB each.
280 Filter map for k, v := range x {
m = {k:v for k, v in m.it
Remove all the elements from the map m that if !p(v) {
ems() if p(v)}
don't satisfy the predicate p.
delete(x, k)
Creates a new map.
Keep all the elements that do satisfy p.
}

} Alternative implementation:
Explain if the filtering happens in-place, i.e. if m
It is safe to use delete while iterating.
for k in list(m):

is reused or if a new map is created.


x is filtered in-place. if p(m[k]): m.pop(k)

Modifies m in-place, but


creates a temporary list of all
the keys.

Go
Rust
Python
Kotlin
Scala
Dart
281 Use a Point as a map key m := map[Point]string{}
m = dict()

You have a Point with integer coordinates x and p := Point{x: 42, y: 5}


p = Point(x=42, y=5)

y. Create a map m with key type Point (or m[p] = "Hello" m[p] = 'Hello'
equivalent) and value type string. Insert "Hello" at
Types comparable with == can be used as map Dictionary keys must be
position (42, 5).
keys. hashable objects. User-defined
classes are hashable by
default.

Alternative implementation:
from collections import n
amedtuple

Point = namedtuple('Poin
t', 'x y')

p = Point(42, 5)

m = {p: "Hello"}
m = {Point(42, 5): "Hello"}
would work just fine, as well!
Naming the point in advance,
has the advantage of using
both p and Point(42, 5) as a
key
282 Use a custom type as map key type Foo struct {

Declare a type Foo, and create a new map with name string

Foo as key type.


x, y int

Mention the conditions on Foo required to make


it a possible map key type. m := make(map[Foo]string)
Foo can be used as a key type if all of its fields are
comparable with ==
283 Split with a custom string separator import "strings" let parts = s.split(sep); parts = s.split(sep)
Build the list parts consisting of substrings of
parts := strings.Split(s, sep) split returns an iterator.

input string s, separated by the string sep.


parts has type []string.
s may have type &str or String.

Alternative implementation:
let parts = s.split(sep).co
llect::<Vec<&str>>();
s may have type &str or String.

Alternative implementation:
let parts: Vec<&str> = s.sp
lit(sep).collect();
s may have type &str or String.
284 Created a zeroed list of integers a := make([]int, n) let a = vec![0; n]; a = [0] * n
Create a new list a (or array, or slice) of size n,
All elements have the default value 0.
where all elements are integers initialized with
the value 0.

Go
Rust
Python
Kotlin
Scala
Dart
285 Set variable to NaN a = float('nan')

Given two floating point variables a and b, set a


Python makes no effort to
to a to a quiet NaN and b to a signalling NaN.
distinguish signaling NaNs
Use standard features of the language only,
from quiet NaNs, and behavior
without invoking undefined behavior.
for signaling NaNs remains
unspecified. Typical behavior is
to treat all NaNs as though
they were quiet.
286 Iterate over characters of a string i := 0
for (i, c) in s.chars().enu for i, c in enumerate(s):
s.forEachIndexed
Print a line "Char i is c" for each character c of for _, c := range s {
merate() {
print(f'Char {i} is { i, c ->

the string s, where i is the character index of c in fmt.Printf("Char %d is %c\n", i, c)


println!("Char {} is {c}')
println("Char
s (not the byte index).
i++
{}", i, c);
$i is $c")

Python strings are sequences


} } of Unicode codepoints (not }
Make sure that multi-byte characters are properly
c is a rune.
s may have type &str or String. bytes).
handled, and count for a single character.
s is assumed encoded in UTF-8.

This first range variable is ignored, as it provides


positions in bytes, instead of runes count.
287 Number of bytes of a string n := len(s) let n = s.len(); n = len(s.encode('utf8'))
Assign to n the number of bytes in the string s.

len counts bytes (not runes). The len method counts the Python strings are sequences
number of bytes, not the number of Unicode codepoints, the
This can be different from the number of
of characters. internal representation is
characters. If n includes more bytes than the
implementation dependent. But
characters per se (trailing zero, length field, etc.)
you can easily determine the
then explain it. One byte is 8 bits.
length of a specific byte
encoding.
288 Check if set contains a value b := x[e] let b = x.contains(&e); b = e in x
Set the boolean b to true if the set x contains the
x has type map[E]bool x has type HashSet
element e, false otherwise.
Alternative implementation:
_, b := x[e]
x has type map[E]struct{}
289 Concatenate two strings s := a + b let s = format!("{}{}", a, s = a + b val s = a + b
Create the string s by concatenating the strings a b);
and b.
This allocates a new String with
a and b concatenated.

Alternative implementation:
let s = a + b;
This adds b to the current
allocation of a, meaning that a
needs to be a mutable String.

Go
Rust
Python
Kotlin
Scala
Dart
290 Sort sublist sub := items[i:j]
items[i..j].sort_by(c); import functools
Sort the part of the list items from index i sort.Slice(sub, func(a, b int) bool {
Sorts a slice of items. items[i:j] = sorted(items
(included) to index j (excluded), in place, using return c(sub[a], sub[b])

the comparator c.
[i:j], key=functools.cmp_
})
to_key(c))
A slice can be sorted in place.
Elements before i and after j must remain c is an old-style comparison
unchanged. function

Alternative implementation:
items[i:j] = sorted(items
[i:j], key=c)
c is a key function, see the
doc.
291 Remove sublist copy(items[i:], items[j:])
items[i:j] = []
Delete all the elements from index i (included) to for k, n := len(items)-j+i, len(items); k <
index j (excluded) from the list items. n; k++ {
Alternative implementation:
items[k] = nil
del items[i:j]
}

items = items[:len(items)-j+i]
Use this when the elements of items have a
pointer type.

The for loop sets unused memory to nil, to avoid a


memory leak.

Alternative implementation:
items = append(items[:i], items[j:]...)
Use this when the elements don't have a pointer
type.
292 Write "Ni Hao" in Chinese to standard output import "fmt" print('Hello World and \u
in UTF-8 4f60\u597d')

Write "Hello World and 你好" to standard output fmt.Println("Hello World and 你好")
in UTF-8.
Strings are UTF-8 by default.
293 Create a stack let mut s: Vec<T> = vec![];
s = []

Create a new stack s, push an element x, then s.push(x);


s.append(x)

pop the element into the variable y. let y = s.pop().unwrap(); y = s.pop()


T is the type of the elements.
In Python the standard
datatype list can be used as a
pop() returns an Option<T>. stack.
294 Print a comma-separated list of integers a = [1, 12, 42]

Given an array a, assign the values 1,12,42 to it, print(*a, sep=', ')

then print out

1, 12, 42

with the minimum width that the integer needs, a


comma and a space after each integer except
the last one.

You might also like