You are on page 1of 103

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

Creative Commons Attribution-ShareAlike 3.0


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

2 Print Hello 10 times for _ in range(10):


(0..9).forEach {
import "fmt" for _ in 0..10 { println! print("Hello\n" * 10.times do

Loop to execute some print("Hello") println("Hell ("Hello"); } 10);


puts "Hello"

code a constant number for i := 0; i < 10; i++ {

Indentation is mandatory o")


0..10 syntax creates range This will print 'Hello' in end
of times fmt.Println("Hello")

}
iterator.
a new line 10 times
}

Alternative implementation: 0..9 is inclusive Alternative implementation:


print("Hello\n"*10) Alternative implementation: The compiler doesn't report 10.times { puts 'Hello' }
Alternative unused variables prefixed with
Sequence repetition is import "fmt"

implementation: an underscore. Alternative implementation:


performed. import "strings"
repeat(10) {
puts "Hello\n" * 10
println("Hell fmt.Println(strings.Repeat("Hello\n", 10)) Alternative implementation:
o")
print!("{}", "Hello\n".repe
} at(10));

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

println("Hel
lo")

3 Create a procedure def finish(name):


fun finish(name: import "fmt" fn finish(name : &str) {
void finish(String def finish( name )

Like a function which print(f'My job here i String) {


println!("My job here i name) {
puts "My job here is done. Go
doesn't return any value, func finish(name string) {

s done. Goodbye {name}') println("My job s done. Goodbye {}", name);


print("My job he odbye #{name}"

thus has only side fmt.Println("My job here is done. Good by


Variable name inside curly here is done. Goo } re is done. Goodby end
effects (e.g. Print to e " + name)

braces will be replaced by its dbye $name")


The actual return type is Unit, e $name.");
Ruby methods always return
standard output) }
value. This is called "f-strings" } typed '()' and can be omitted } something; in this case nil, the return
There is no return type in the signature, before the
introduced in Python version from function signature. value of puts

{.
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).



Python
Kotlin
Go
Rust
Dart
Ruby
4 Create a function def square(x):
fun square(x: In func square(x int) int {
fn square(x : u32) -> u32 { int square(int x) def square(x)

Create a function which return x*x t) = x * x return x*x


x * x } => x * x; x*x

returns the square of an } end


You don't have to explicitly Last expression in block is used
integer
write the return type The return type is after the parameter list as a return value. The last expression is returned by
default.
Alternative implementation:
def square(x):
Alternative implementation:
return x**2 def square(x) = x*x

You can use power operator Ruby 3.0


5 Create a 2D Point data from dataclasses import d data class Point type Point struct {
struct Point {
class Point {
Point = Struct.new(:x, :y)
structure ataclass (val x: Float, va x, y float64
x: f64,
double x, y;
Instantiate like this :
Declare a container type l y: Float) } y: f64,
}
@dataclass
Point.new(1.0,1.0)
for two floating-point }
numbers x and y class Point:

Alternative
x: float

Alternative implementation: implementation:


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

double x, y;

Point(this.x, th
is.y);

With constructor,
which you will almost
always have.
6 Iterate over list values for x in items:
items.forEach { d for _, x := range items {
for x in items {
items.forEach(doSo items.each{|x| do_something( x
Do something with each doSomething( x ) oSomething(it) } doSomething(x)
do_something(x);
mething); )}
item x of an array-like } }
collection items, Alternative Alternative implementation:
You have to explicitly ignore the index loop
regardless indexes. implementation: Alternative implementation:
variable, with the blank identifier _ items.each do |x|

items.forEach(::d items.into_iter().for_each do_something( x )

oSomething) (|x| do_something(x)); end


Using a function
reference.

Alternative
implementation:
for (x in items)
doSomething(x)

Python
Kotlin
Go
Rust
Dart
Ruby
7 Iterate over list indexes for i, x in enumerate(ite items.forEachInde import "fmt" for (i, x) in items.iter(). for (var i = 0; i items.each_with_index do |x, i|

and values ms):


xed { i, x ->
enumerate() {
< items.length; i+ puts "Item #{i} = #{x}"

Print each index i with its for i, x := range items {

print i, x print("i=$i x= println!("Item {} = +) {


end
value x from an array- fmt.Printf("Item %d = %v \n", i, x)

$x")
{}", i, x);
print('index=$i, See also the one-liner Ruby solution
like collection items }
} } value=${items
The range clause gives you index i and value x at [i]}');
Alternative implementation:
the same time as loop variables Alternative implementation: } items.each_index{|i| puts "Item
items.iter().enumerate().fo %d = %s" % [i, items[i]]}
r_each(|(i, x)| {
Alternative
println!("Item {} = implementation:
{}", i, x);
items.asMap().forE
}) ach((i, value) {

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

});

An alternative, but not


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

Create a new map object 2)


"two": 2

x, and provide some let mut x = BTreeMap::new


use it only if };
(key, value) pairs as ();

performance isn't x.insert("one", 1);

initial content.
critical, see docs x.insert("two", 2);

Alternative Something different than a


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

val x = mutableMa
pOf<String, Integ
The function new of the type
er>().apply { thi
BTreeMap returns a usable
s["one"] = 1; thi
map.

s["two"] = 2 }
The map is stored mutable in the
variable x.

Alternative
implementation:
Maps in Rust are generic but the
val x = mutableMa type is determined by the
pOf<String, Integ compiler based on the later
er>()
usage.

x["one"] = 1
A line such as `x.insert(1, "one")`
x["two"] = 2 would therefore not compile.

Alternative implementation:
use std::collections::HashM
ap;

let x: HashMap<&str, i32> =


[

("one", 1),

("two", 2),

].into_iter().collect();

Python
Kotlin
Go
Rust
Dart
Ruby
9 Create a Binary Tree class Node:
data class Node(
type BinTree struct {
struct BinTree<T> {
class Node<T> {
Node = Struct.new(:left, :righ
data structure def __init__(sel     val key: Int,
Value valueType
value: T,
final T value;
t, :value)

The structure must be f, data):


    val left: Nod Left *BinTree
left: Option<Box<BinTre Node<T> left, ri parent = Node.new(Node.new, Nod
recursive because left self.data e? = null,
Right *BinTree
e<T>>>,
ght;
e.new)
child and right child are = data
    val right: No }
right: Option<Box<BinTr Node(this.value, Should also have a place to store the
binary trees too. A node self.left de? = null
ee<T>>>,
{this.left, this.r value

has access to children = None


) } ight});

nodes, but not to its self.righ }


parent. 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

Python
Kotlin
Go
Rust
Dart
Ruby
10 Shuffle a list from random import shuffl mutableList.shuff import "math/rand" extern crate rand;
x.shuffle(); x.shuffle
Generate a random e le() use rand::{Rng, StdRng};
for i := range x {
This alters the content
permutation of the Alternative implementation:
shuffle(x) Only mutable lists j := rand.Intn(i + 1)
let mut rng = StdRng::new of x.
elements of list x
can be shuffled in- x[i], x[j] = x[j], x[i]
().unwrap();
shuffled_list = x.shuffle
This alters the list Alternative
place. } rng.shuffle(&mut x);
implementation:
Alternative implementation: This alters the slice content.
Requires the rand crate
Alternative var shuffled = x.t
import random This requires no extra allocation. (https://crates.io/crates/rand)
implementation: oList()..shuffle
random.shuffle(list) val newList = lis Alternative implementation: Alternative implementation: ();
random.shuffle is a inbuilt t.shuffled()
import "math/rand" use rand::seq::SliceRandom;
This keeps x
function that will shuffle the Immutable lists use rand::thread_rng; unchanged.
data. y := make([]T, len(x))

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]

11 Pick a random element import random list.random() import "math/rand" use rand::{self, Rng}; x[new Random().nex x.sample
from a list tInt(x.length)];
List x must be non- random.choice(x) x[rand.Intn(len(x))] x[rand::thread_rng().gen_ra
empty. nge(0..x.len())]
Alternative implementation: gen_range returns a number
import "math/rand" between 0 (inclusive) and x.len()
(exclusive)
func pickT(x []T) T {

return x[rand.Intn(len(x))]
Alternative implementation:
}
use rand::seq::SliceRandom;
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.

Python
Kotlin
Go
Rust
Dart
Ruby
12 Check if list contains a x in list x in list func Contains(list []T, x T) bool {
list.contains(&x); list.contains(x); list.include? x
value for _, item := range list {

This indirectly calls See also more general


Check if list contains a Alternative if item == x {

list._contains__() and returns alternative implementations.


value x. implementation: return true

True or False
list is an iterable finite }
Alternative implementation:
list.contains(x)
container. }
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 for k, v in mymap.items mymap.entries.for import "fmt" use std::collections::BTree mymap.forEach((k, mymap.each {|k, x| puts "Key= #
and values ():
Each { print("${i Map; v) => print('Key= {k} Value=#{x}"}
Access each key k with for k, x := range mymap {

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


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

e}") }
associative array } println!("Key={key}, Va
mymap, and print them. Do not rely on the order of the traversal ! The order lue={val}", key=k, val=x);

is undefined and is intentionaly randomized by the }

Go runtime. You can also print collections in


a 'nice' way with `println!("{:?}",
mymap);` which is the Debug-
representation. You can also use
"{:#?}" for the pretty version.

This example works the same if


you replace BTreeMap with
HashMap.
14 Pick uniformly a import random import "math/rand" extern crate rand;
import 'dart:mat rand(a...b)
random floating point use rand::{Rng, thread_rn h';
random.uniform(a,b) func pick(a, b float64) float64 {
(Presuming a and/or b are floats) a
number in [a..b) g};
return a + (rand.Float64() * (b-a))
double pick(num a, range constructed using ... excludes
Pick a random number The end-point value b may or
} thread_rng().gen_range(a.. num b) => a + new the end value.
greater than or equals to may not be included in the
a, strictly inferior to b. range depending on floating- b); Random().nextDoubl
Precondition : a < b. point rounding If you need to generate a lot of e() * (b - a);

random stuff, save the


thread_rng as a variable so it is
only initialized once.

Python
Kotlin
Go
Rust
Dart
Ruby
15 Pick uniformly a import random fun pick(a: Int, import "math/rand" extern crate rand;
import 'dart:mat rand(a..b)
random integer in [a..b] b: Int): Int {
use rand::distributions::{I h';
Pick a random integer random.randint(a,b) func pick(a,b int) int {

return (a.. ndependentSample, Range};


greater than or equals to Upper bound b is included. return a + rand.Intn(b-a+1)
int pick(int a, in
b).random()

a, inferior or equals to b. } fn pick(a: i32, b: i32) -> t b) => a + new Ra


}
Precondition : a < b. (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 def dfs(bt):


func (bt *BinTree) Dfs(f func(*BinTree)) {
traverse(Node bt, def dfs(f, bt)

of a binary tree if bt is None:


if bt == nil {
f(value)) {
dfs(f, bt.left) if bt.left

Call a function f on every return


return
if (bt == null) f.(bt)

node of binary tree bt, in dfs(bt.left)


}
return;
dfs(f, bt.right) if bt.right

depth-first infix order f(bt)


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

Recursive DFS. bt.Right.Dfs(f)


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.
17 Create a Tree data class Node:
type Tree struct {
struct Node<T> {
class Node<T> {
Node = Struct.new(:children)

structure def __init__(self, va Key keyType


value: T,
final T value;
parent = Node.new([])

The structure must be lue, *children):


Deco valueType
children: Vec<Node<T>>,
final List<Node< parent.children << Node.new([])
recursive. A node may self.value = valu Children []*Tree
} T>> children;

have zero or more e


}
Node(this.value,
children. A node has self.children = l this.children);

keyType should be easily comparable.

access to its children ist(children) }

valueType is a type of value associated with


nodes, but not to its
current node.

parent.
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).

Python
Kotlin
Go
Rust
Dart
Ruby
18 Depth-first traversing def DFS(f, root):
func (t *Tree) Dfs(f func(*Tree)) {
pub struct Tree<V> {
traverse(Tree nod def dfs(f, node)

of a tree f(root)
if t == nil {
children: Vec<Tree<V>>,
e, f(value)) {
f.(node)

Call a function f on every for child in roo return


value: V
f(node.value);
node.children.each do |child|

node of a tree, in depth- t:


}
}
for (var child i dfs(f, child)

first prefix order DFS(f, ch f(t)


n node.children) {
end

ild) for _, child := range t.Children {


impl<V> Tree<V> {
traverse(chil end
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.
19 Reverse a list x = reversed(x) x.reverse() for i, j := 0, len(x)-1; i < j; i, j = i+1, let y: Vec<_> = x.into_iter x = x.reversed.toL x.reverse!
Reverse the order of the j-1 {
().rev().collect(); ist();
returns an iterable.
MutableLists or Reverses self in place.
elements of list x.
x[i], x[j] = x[j], x[i]

on lists this creates a new list. Arrays can be Instead of Vec, you can also use
This may reverse "in- }
reversed in place. any other data structure that
place" and destroy the Alternative implementation: This loop reverts "in-place" (in the original list, not implements Iterator.
original ordering. Alternative
y = x[::-1] creating a new one).
implementation: Alternative implementation:
Creates a new, reversed list.
x = x.reversed() x.reverse();
Alternative implementation: Immutable lists but
x.reverse() not in-place.
Reverses list 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.

Python
Kotlin
Go
Rust
Dart
Ruby
20 Return two values def search(m, x):
fun search(m: Arr func search(m [][]int, x int) (bool, int, i fn search<T: Eq>(m: &Vec<Ve class Position {
def search(m, x)

Implement a function for idx, item in enum ay<Array<Int>>, nt) {


c<T>>, x: &T) -> Option<(us int i, j;
m.each_with_index do |row, i|

search which looks for erate(m):


x: Int): Pair<In for i := range m {
ize, usize)> {
Position(this.i, row.each_with_index do |val
item x in a 2D matrix m.
if x in item:
t, Int>? {
for j, v := range m[i] {
for (i, row) in m.iter this.j);
ue, j|

Return indices i, j of the return idx, i m.forEachInde if v == x {


().enumerate() {
}
return i, j if value == x

matching cell.
tem.index(x) xed { i, row ->
return tru for (j, column) in Position search(Li end

Think of the most row.forEa e, i, j


row.iter().enumerate() {
st<List> m, x) {
end

idiomatic way in the chIndexed { j, va }


if *column == * for (var i = 0; nil

language to return the lue ->


}
x {
i < m.length; i++) end
two values at the same if (v }
return Some {

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

eturn Pair(i, j)
Go functions may return multiple values.
}
for (var j =
}
This function returns 3 values : one to indicate if x }
0; j < line.lengt
}
was found or not, and two for the coordinates. h; j++) {

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

} This returns an optional tuple. return new


Position(i, j);

return null;

21 Swap values a, b = b, a a = b.also { b = a, b = b, a std::mem::swap(&mut a, &mut var tmp = a;


a, b = b, a
Swap values of variables a } b);
a = b;

a and b b = tmp;
Alternative implementation:
let (a, b) = (b, a);

This uses pattern matching and


destructuring of tuples to swap
values.

Python
Kotlin
Go
Rust
Dart
Ruby
22 Convert string to i = int(s) s.toInt() import "strconv" let i = s.parse::<i32>().un var i = int.parse i = s.to_i
integer wrap(); (s);
i, err := strconv.Atoi(s) to_i returns 0 if s is not a valid
Extract integer value i Alternative This panics if s is not a valid number.
from its string implementation: Atoi(s) is shorthand for ParseInt(s, 10, 0). It yields
number.

representation s (in radix type int. Alternative implementation:


val i = s.toInt() s is parsed to 32-bits signed
10)
Alternative implementation: integer here (change number contrato_nf['items']['issueDat
type if needed). e'] = data
import "strconv"

i, err := strconv.ParseInt(s, 10, 0) Alternative implementation:

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 s = '{:.2f}'.format(x) s = "%.2f".format import "fmt" let s = format!("{:.2}", var s = x.toString s = "%.2f" % x
string with 2 decimal (x) x); AsFixed(2);
places s := fmt.Sprintf("%.2f", x)
Alternative implementation: Only works up to
Given a real number x,
s = f'{x:.2f}' 1e+21, then it uses
create its string
exponential notation.
representation s with 2 f' → a formatted string

decimal digits following {x: → formatting x to

the dot. .2f → a fixed-point number with


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

Python
Kotlin
Go
Rust
Dart
Ruby
25 Send a value to import Queue import "fmt" use std::thread;
import "dart:isola queue = Queue.new

another thread use std::sync::mpsc::channe te"; thread = Thread.new do

Share the string value q = Queue()


go func() {

l; puts queue.pop

"Alan" with an existing v := <-ch


sendPort.send("val
end

running process which t = Thread(target=worker)


fmt.Printf("Hello, %v\n", v)
let (send, recv) = channel ue");
queue << "Alan"

will then display "Hello, t.daemon = True


}()
();
Ports are used for thread.join

Alan" t.start()
communicating
ch <- "Alan" thread::spawn(move || {
between individually
q.put("Alan") The receiver goroutine blocks reading the chan loop {
running isolates. The
The Queue module has been string named ch.
let msg = recv.recv receiving isolate has
renamed to queue in Python 3. The current goroutine sends the value to ch.
().unwrap();
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 x = [[0] * n for _ in ran val x = Array(m, const m, n = 3, 4
let mut x = vec![vec![0.0f6 var x = new List.g x = Array.new(m) { Array.new(n)
array ge(m)] { DoubleArray(n) var x [m][n]float64 4; N]; M]; enerate(m, (_) => }
Declare and initialize a })
new List(n));
Do not just "multiply by m", m, n must be constant for this syntax to be valid.

matrix x having m rows Alternative implementation:


which would duplicate the The type of x is Here x is of type [3][4]float64, it is not a slice.
and n columns,
references to the inner arrays. Array<DoubleArray>. let mut x = [[0.0; N] ; M];
containing real numbers. Alternative implementation:
In other words, an This works only when M and N
Alternative implementation: array of arrays. func make2D(m, n int) [][]float64 {
are constant.

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


Elements have type f64

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.

Python
Kotlin
Go
Rust
Dart
Ruby
27 Create a 3-dimensional x = [[[0 for k in range val x = Array(m, const m, n, p = 2, 2, 3
let x = vec![vec![vec![0.0f var x = new List.g x = Array.new(m) { Array.new(n)
array (p)] for j in range(n)] f { Array(n, { Arra var x [m][n][p]float64 64; p]; n]; m]; enerate(m, (_) =>
{ Array.new(p) } }
Declare and initialize a or i in range(m)] yDouble(p) } ) } ne
m, n, p must be constant for this syntax to be valid.
m, n, p don't have to be
3D array x, having ) w List.generate(n,
xrange is not supported in Here x is of type [2][2][3]float64, it is not a slice. constants
dimensions boundaries (_) =>

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

x = numpy.zeros((m,n,p)) Stack-allocated array.

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

NumPy is a third-party library for i := range x {


gr
M, N, P are constants.
for scientific computing. x[i] = make([][]float64, n)
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 items = sorted(items, key items.sortedBy { import "sort" items.sort_by(|a,b| a.p.cmp items.sort((a, b) items.sort_by(&:p)
Sort elements of array- =lambda x: x.p) it.p }
(&b.p)); => Comparable.comp
like collection items in type ItemPSorter []Item

The lambda expression pulls are(a.p, b.p));


ascending order of x.p, func (s ItemPSorter) Len() int{ return len
out the field you want to sort Alternative implementation:
where p is a field of the (s) }

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


type Item of the objects func (s ItemPSorter) Less(i,j int) bool{ re
reverse order, add implementation:
in items. turn s[i].p<s[j].p }

reverse=True to the argument func (s ItemPSorter) Swap(i,j int) { s[i],s items.sort((a, b)


list. [j] = s[j],s[i] }
=> (a.p).compareTo
(b.p));
Alternative implementation:
func sortItems(items []Item){

from operator import attr sorter := ItemPSorter(items)

getter sort.Sort(sorter)

items = sorted(items, key }

=attrgetter('p')) The standard way is to declare a new type


We use attrgetter to avoid ItemSorter as a slice of Item, and carefully
having to write a lambda. The implement method Less.
Operator module contains lots
Alternative implementation:
of useful functions that can be
import "sort"
passed to higher-order
functions. less := func(i, j int) bool {

return items[i].p < items[j].p

sort.Slice(items, less)

This is the diomatic way since Go 1.8.



Python
Kotlin
Go
Rust
Dart
Ruby
29 Remove item from list, del items[i] items.removeAt(i) items = append(items[:i], items[i+1:]...) items.remove(i) items.removeAt(i); items.delete_at(i)
by its index
This alters the original list. If items elements are pointers or structs with A negative value for i is also valid, -1
Remove i-th item from
pointers, then refer to the SliceTricks page to avoid refering to the last element from
list items.

memory leaks. items, -2 to the item before the last.


This will alter the original
list or return a new list, Alternative implementation:
depending on which is
copy(items[i:], items[i+1:])

more idiomatic.

items[len(items)-1] = nil

Note that in most


items = items[:len(items)-1]
languages, the smallest
valid value for i is 0. This code is for pointer value type, and has no
memory leak.
30 Parallelize execution of from multiprocessing impo import kotlinx.co import "sync" use std::thread; threads = 1000.times.map do |i|

1000 independent rt Pool routines.* Thread.new { f(i) }

tasks wg := sync.WaitGroup{}
let threads: Vec<_> = (0..1
end

Launch the concurrent pool = Pool()


fun main() = runB wg.Add(1000)
000).map(|i| {

threads.join
execution of procedure f for i in range(1, 1001):
locking {
for i := 1; i <= 1000; i++ {
thread::spawn(move
with parameter i from 1 pool.apply_async repeat(1000) go func(j int) {
|| f(i))

to 1000.
(f, [i]) {
f(j)
}).collect();

Tasks are independent launch {


wg.Done()

and f(i) doesn't return f(it)


}(i)
for thread in threads {

any value.
}
}
thread.join();

Tasks need not run all at }


wg.Wait() }
the same time, so you } The current value of i is captured, and a goroutine If you don't join the threads, the
may use a pool. 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)

Python
Kotlin
Go
Rust
Dart
Ruby
31 Recursive factorial def f(i):
fun f(i: Int): In func f(i int) int {
fn f(n: u32) -> u32 {
f(i) => (i == 0) ? f = Hash.new { |hash, i| hash
(simple) if i == 0:
t = when (i) {
if i == 0 {
if n < 2 {
1 : i * f(i - 1); [i] = i * hash[i -1] }

Create the recursive return 1


0 -> 1
return 1
1
f[0] = 1

function f which returns else:


else -> i * f }
} else {
Note that f is not a function but plain
the factorial of the non- return i * f(i-1) (i - 1)
return i * f(i-1)
n * f(n - 1)
old Hash used as a cache for
negative integer i, }
} }
performance.
calculated from f(i-1) }
Alternative Alternative implementation:
implementation: Alternative implementation: fac = Hash.new {|h, i| h[i] = i
fun f(i: Int) = i fn factorial(num: u64) -> u * h[i-1] }.tap {|h| h[0] = 1 }
f (i == 0) 1 else 64 {

i * f(i - 1)
match num {

0 | 1 => 1,

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

match arm for 0|1 checks if the


numbers are either 0 or 1

Python
Kotlin
Go
Rust
Dart
Ruby
32 Integer exponentiation def exp(x, n):
fun exp(x: Int, func exp(x, n int) int {
fn exp(x: u64, n: u64) -> u int exp(int x, int def exp(x, n)

by squaring return x**n


n: Int): Int = wh switch {
64 {
n) {
x ** n

Create function exp en {


case n == 0:
match n {
if (n == 0) retu end
which calculates (fast) n == 0 -> 1
return 1
0 => 1,
rn 1;

the value x power n.


n == 1 -> x
case n == 1:
1 => x,
if (n == 1) retu Alternative implementation:
x and n are non- n % 2 == 0 -> return x
i if i % 2 == 0 => rn x;
def exp(x, n)

negative integers. exp(x * x, n / 2)


case n%2 == 0:
exp(x * x, n / 2),
var r = exp(x * return 1 if n == 0

else -> x * e return exp(x*x, n/2)


_ => x * exp(x * x, x, n ~/ 2);
return x if n == 1

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

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

}
} end
}

Warning: type int quickly overflows Alternative


implementation:
int exp(int x, int
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.
33 Atomically read and import threading import "sync" let mut x = x.lock().unwrap x = f(x); require 'atomic'
update variable ();

lock = threading.Lock()
var lock sync.RWMutex
Dart is single- x = Atomic.new(0)

Assign to the variable x *x = f(x); threaded. Other x.update { |x| f(x) }


the new value f(x),
lock.acquire()
lock.Lock()
Assuming x is created like this:
threads run in
making sure that no
try:
x = f(x)
`let x = Mutex::new(0);` separate isolates.

other thread may modify


x between the read and x = f(x)
lock.Unlock()
the write. finally:
You need to lock whenever accessing x.
lock.release()

Alternative implementation:
import threading

with threading.Lock():

x = f(x)


Python
Kotlin
Go
Rust
Dart
Ruby
34 Create a set of objects class T(object):
x := make(map[T]bool) use std::collections::HashS var x = new Set<T> require 'set'
Declare and initialize a pass
et; ();
There is no built-in Set type, but you can create a x = Set.new
set x containing unique
Map with key type T and boolean value (which will let x: HashSet<T> = HashSe
objects of type T. x = set(T()) be ignored). t::new();

Alternative implementation: Alternative implementation:


class T:
x := make(map[T]struct{})
...
The struct{} type is space efficient because it
occupies zero bytes in memory.

s = set(T() for _ in rang But it is less intuitive to use than a bool value.
e(x))
`...` is a placeholder, `pass` can
also be used
35 First-class function : def compose(f, g):
func compose(f func(A) B, g func(B) C) func fn compose<'a, A, B, C, G, typedef R Func<T,R def compose(f, g)

compose return lambda a: g(f (A) C {


F>(f: F, g: G) -> Box<Fn(A) >(T arg);
-> x { g.(f.(x)) }

Implement a function (a)) return func(x A) C {


-> C + 'a>
end

compose (A -> C) with return g(f(x))


where F: 'a + Fn(A) Func<A,C> compose
We could have used a named
parameters f (A -> B) }
-> B, G: 'a + Fn(B) -> C
(B f(A x), C g(B
function but a lambda is shorter
and g (B -> C), which } {
x)) => (A x) => g
returns composition Box::new(move |x| g (f(x))
Functions are first-class citizens in Go. They are
function g ∘ f (f(x)))

passed as arguments and as return values. 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))

}

Python
Kotlin
Go
Rust
Dart
Ruby
36 First-class function : def compose(f, g):
func composeIntFuncs(f func(int) int, g fun fn compose<'a, A, B, C, G, compose(f, g) => def compose(f, g)

generic composition return lambda x: c(int) int) func(int) int {


F>(f: F, g: G) -> Box<Fn(A) (x) => g(f(x)); -> x { g.(f.(x)) }

Implement a function g(f(x)) return func(x int) int {


-> C + 'a>
end
compose which returns return g(f(x))
where F: 'a + Fn(A)
This is the same as for non-
composition function g ∘  }
-> B, G: 'a + Fn(B) -> C
Alternative implementation:
generic composition
f for any functions f and } {
def compose(f, g)

g having exactly 1 Box::new(move |x| g


Go doesn't have support for generics so the f >> g

parameter. (f(x)))

functions must take and return concrete types.


end
}
Needs Ruby >= 2.6
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))

37 Currying from functools import par type PayFactory func(Company, *Employee, *E fn add(a: u32, b: u32) -> u adder = -> a, b { a + b }

Transform a function that tial mployee) Payroll


32 {
add_two = adder.curry.(2)

takes multiple arguments curry(f(a, b), a)


a + b
add_two.(5) # => 7
into a function for which def f(a):
=> (b) => f(a, b);
type CustomPayFactory func(*Employee) Payro }

some of the arguments return lambda b: Simple currying of


ll

are preset. a+b


binary funtion.
let add5 = move |x| add(5,
func CurryPayFactory(pf PayFactory,company x);

print (f(2)(1))

Company, boss *Employee) CustomPayFactory {

return func(e *Employee) Payroll {

#add_to_two = partial(f,
return pf(company, boss, e)

2)
}

}
The currying function is not generic, it must be
written for each type of currying needed.
38 Extract a substring t = s[i:j] val t = s.substri t := string([]rune(s)[i:j]) extern crate unicode_segmen var t = s.substrin t = s[i..j-1]
Find substring t ng(i, j) tation;
g(i, j);
Slicing works on strings. convert to []rune because some characters are two In ruby j is included by default

consisting in characters i use unicode_segmentation::U


or more bytes. s = "test"

(included) to j (excluded) nicodeSegmentation;


t = "s[0..1] => "te"
of string s.

Character indices start at let t = s.graphemes(true).s


0 unless specified kip(i).take(j - i).collec
otherwise.
t::<String>();
Make sure that multibyte Treats the 'character indexes' as
characters are properly indices of 'extended grapheme
handled. clusters' as defined by Unicode.

Alternative implementation:
use substring::Substring;

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



Python
Kotlin
Go
Rust
Dart
Ruby
39 Check if string ok = word in s val ok = s.contai import "strings" let ok = s.contains(word); var ok = s.contain ok = s.include?(word)
contains a word ns(word) s(word);
Set boolean ok to true if ok := strings.Contains(s, word)
Argument of contains
string word is contained
must be a Pattern.
in string s as a substring,
or to false otherwise.
40 Graph with adjacency from collections import d type Vertex struct{
Vertex = Struct.new(:x, :y, :z)

lists efaultdict Id int


Graph = Struct.new(:vertex, :ne
Declare a Graph data Label string
ighbours)

structure in which each class Vertex(set): pass

Neighbours map[*Vertex]bool

Vertex has a collection class Graph(defaultdict):

}
v = Vertex.new(1, 2, 3)

of its neighbouring def __init__(self, *pat


neighbours = [ Vertex.new(2, 3,
vertices. hs):

type Graph []*Vertex 4), Vertex.new(4, 5, 6) ]

self.default_factory
The map is used as a Set of Vertex pointers.
graph = Graph.new(v, neighbour
= Vertex

Graph is a list of all the Vertex pointers. s)


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 t = s.decode('utf8')[::- val t = s.reverse runes := []rune(s)


let t = s.chars().rev().col var t = new Strin t = s.reverse
Create string t 1].encode('utf8') d() for i, j := 0, len(runes)-1; i < j; i, j = lect::<String>(); g.fromCharCodes(s.
containing the same i+1, j-1 {
runes.toList().rev
collect is a function with a
characters as string s, in Alternative implementation: runes[i], runes[j] = runes[j], runes[i]
ersed);
generic return type, so we must
reverse order.
}

t = s[::-1] explicitly specify that we want a This does reverse the


Original string s must t := string(runes) String back, either by annotating order of the runes,
remain unaltered. Each
This takes care of multi-byte runes, which count as t's type as a String, or by however it may handle
character must be
a single character. specifying with the so-called improperly some
handled correctly
"turbofish" syntax. dependant runes like
regardless its number of
diacritics.
bytes in memory. Alternative implementation:
let t: String = s.chars().r Alternative
ev().collect(); implementation:
var t = s.split
('').reversed.join
();


Python
Kotlin
Go
Rust
Dart
Ruby
42 Continue outer loop for v in a:
mainloop:
'outer: for va in &a {
main() {
a.each do |v|

Print each item v of list a try:


for _, v := range a {
for vb in &b {
var a = [1, 2, catch :matched do

which is not contained in for u in b:


for _, w := range b {
if va == vb {
3];
b.each do |u|

list b.
if v == u:
if v == w {
continue 'oute var b = [2, 3];
throw :matched if v == u

For this, write an outer raise Exc continue ma r;


end

loop to iterate on a and eption()


inloop
}
outer: for (var puts v

an inner loop to iterate print(v)


}
}
v in a) {
end

on b. except Exception:
}
println!("{}", va);
for (var w in end
continue
fmt.Println(v)
}
b) {
Idiomatic ruby would be: puts a-b
Note that using two loops like } 'outer is a label used to refer to if (w == v)
this in python is by itself very mainloop is a label used to refer to the outer loop. the outer loop. Labels in Rust continue outer;

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

be wise to define a custom print(v);

exception to avoid hiding "real" }

exceptions. }

43 Break outer loop class BreakOuterLoop (Exc mainloop:


'outer: for v in m {
OUTER: for (var i negative_value = catch :negativ
Look for a negative eption): pass
for i, line := range m {
'inner: for i in v {
= 0; i < m.length; e do

value v in 2D integer for _, v := range line {


if i < 0 {
i++) {
matrix.each do |row|

matrix m. Print it and try:


if v < 0 { println!("Found for (var j = 0; row.each do |value|

stop searching. position = None


fmt.Println {}", i);
j < m[i].length; j throw :negative, value if
for row in m:
(v)
break 'outer;
++) {
value < 0

for column in m[r break mainl }


if (m[i][j] < end

ow]:
oop
}
0) {
end

if m[row][col }
} print("Negat end

umn] == v:
}
Loop label syntax is similar to ive value found at
position } lifetimes. $i,$j: ${m[i] puts negative_value
= (row, column)
mainloop is a label used to refer to the outer loop. [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:
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))

Python
Kotlin
Go
Rust
Dart
Ruby
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.insert(i, x) s = append(s, 0)
s.insert(i, x); s.insert(i, x); s.insert(i, x)
Insert element x at copy(s[i+1:], s[i:])

position i in list s. s[i] = x


Further elements must
Extend slice by 1 (it may trigger a copy of the
be shifted to the right.
underlying array).

Then shift elements to the right.

Then set s[i].



Python
Kotlin
Go
Rust
Dart
Ruby
45 Pause execution for 5 import time Thread.sleep(5000 import "time" use std::{thread, time}; import 'dart:io'; sleep 5
seconds L)
Sleep for 5 seconds in time.sleep(5) time.Sleep(5 * time.Second) thread::sleep(time::Duratio sleep(const Durati
current thread, before Unit is Duration, an alias for int64 representing a n::from_secs(5)); on(seconds: 5));
proceeding with next number of nanoseconds.
sleep is only available
instructions. 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.

Python
Kotlin
Go
Rust
Dart
Ruby
46 Extract beginning of t = s[:5] val t = s.take(5) t := string([]rune(s)[:5]) let t = s.char_indices().nt var t = s.substrin t = s[0, 5]
string (prefix) h(5).map_or(s, |(i, _)| &s g(0, 5);
This "incurs a run-time cost" proportional to len(s).
Create string t consisting [..i]); Alternative implementation:
of the 5 first characters
Rust strings are encoded in t = s.slice(0, 5)
of string s.

UTF-8, and can be multiple


Make sure that multibyte
bytes wide, which text Alternative implementation:
characters are properly
processing code must account t = s.slice(0...5)
handled.
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 = s[-5:] t := string([]rune(s)[len([]rune(s))-5:]) let last5ch = s.chars().cou var n = s.length;
t = s[-5..-1]
Create string t consisting nt() - 5;
var t = s.substrin
Convert to []rune because some characters are
in the 5 last characters let t: String = s.chars().s g(n-5, n); Alternative implementation:
two or more bytes long.
of string s.
kip(last5ch).collect();
t = s[-5..]
Make sure that multibyte
characters are properly endless ranges were added in Ruby
handled. 2.6
48 Multi-line string literal s = """Huey
val s =
s := `Huey
let s = "line 1
var s = '''A
s = "Spanning

Assign to variable s a Dewey


"""
Dewey
line 2
multi-line
string

string literal consisting in Louie""" This is my


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

Raw string literals do not multi-line

process any escapes. string""";

Triple double quotes.



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

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


of input string s, Warning: you may get empty strings as items in
consecutive ASCII whitespace
separated by one or chunks because of leading spaces, trailing Alternative implementation:
are regarded as a single
more space characters. spaces, and repeated spaces.
separator, and the result will let chunks: Vec<_> = s.spli
contain no empty strings at the Alternative implementation: t_ascii_whitespace().collec
start or end if the sequence t();
import "strings"
has leading or trailing This regards all ASCII
whitespace. Consequently, chunks := strings.Fields(s)
whitespace as separators,
splitting an empty sequence or chunks has type []string.
including \t and \n.
a sequence consisting solely of Fields treats repeated spaces as a single
ASCII whitespace without a separator. Alternative implementation:
specified separator returns []. let chunks: Vec<_> = s.spli
t(' ').collect();

Warning: this returns some


empty strings in chunks, in case
of multiple consecutive spaces
in the s.
50 Make an infinite loop while True:
while (true) { } for {
loop {
while (true) {
loop do

Write a loop that has no pass // Do something


// Do something
// do something
# endless joy

end clause. } } } end


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

51 Check if map contains k in m import kotlin.col _, ok := m[k] use std::collections::HashM m.containsKey(k) m.include?(k)

key lections.map ap;


ok is true if m contains a value for key k. The value
Determine whether map Alternative implementation:
map.containsKey(k itself is ignored. m.contains_key(&k)
m contains an entry for
ey) m.key?(k)
key k
returns a Boolean
Alternative implementation:
m.has_key?(k)

52 Check if map contains v in m.values() func containsValue(m map[K]T, v T) bool {


use std::collections::BTree m.containsValue m.value?(v)
value for _, x := range m {
Map; (v);
Determine whether map if x == v {

m contains an entry with let does_contain = m.values


return true

value v, for some key. ().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).

Python
Kotlin
Go
Rust
Dart
Ruby
53 Join a list of strings y = ', '.join(x)
val y = listOf import "strings" let y = x.join(", "); y = x.join(', '); y = x.join(", ")
Concatenate elements of (x).joinToString
This works if x contains only y := strings.Join(x, ", ") Note that join() used to be
string list x joined by the (", ")
strings. named connect() .
separator ", " to create a This works only if x has type []string.
single string y. Alternative implementation:
y = ', '.join(map(str,
x))
This works even if some
elements in x are not strings.
54 Compute sum of s = sum(x) val numbers = lis s := 0
x.iter().sum() var s = x.fold(0, s = x.sum
integers tOf(1, 2, 3, 4)
for _, v := range x {
(a, b) => a + b);
sum is a built-in function. Works since Ruby 2.4
Calculate the sum s of val sum = number s += v
Alternative implementation:
the integer list or array x. s.sum() } Alternative implementation:
let s = x.iter().sum::<i32>
Such explicit loops are idiomatic in Go. (); s = x.reduce(:+)
This was idiomatic before Ruby 2.4
55 Convert integer to s = str(i) val s = i.toStrin import "strconv" let s = i.to_string(); var s = "$i";
s = i.to_s
string g()
s := strconv.Itoa(i) s has type String
Create the string
representation s (in radix When i has type int. Alternative implementation:
10) of integer value i.
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

Python
Kotlin
Go
Rust
Dart
Ruby
56 Launch 1000 parallel from multiprocessing impo import kotlinx.co import "sync" use std::thread; threads = 1000.times.map do |i|

tasks and wait for rt Pool routines.* Thread.new { f(i) }

completion var wg sync.WaitGroup


let threads: Vec<_> = (0..1
end

Fork-join : launch the def f(i):


(1..1000)
wg.Add(1000)
000).map(|i| thread::spawn
threads.join
concurrent execution of i * i
.map { i ->
for i := 1; i <= 1000; i++ {
(move || f(i))).collect();

procedure f with Coroutine go func(i int) {

parameter i from 1 to with Pool(1000) as p:


Scope(Dispatcher f(i)
for t in threads {

1000.
p.map(func=f, ite s.Default).async wg.Done()
t.join();

Tasks are independent rable=range(1, 1001))


{
}(i)
}

and f(i) doesn't return f(i)


}

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

Tasks need not run all at }


fmt.Println("Finished")
the same time, so you .awaitAll()
It is necessary to capture the current value of loop
may use a pool.
print("Finished") variable i. See
Wait for the completion Leverages kotlin's https://github.com/golang/go/wiki/CommonMistakes
of the 1000 tasks and coroutines to run
then print "Finished". 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
*/ }
57 Filter list y = list(filter(p, x)) val y = x.filter y := make([]T, 0, len(x))
let y: Vec<_> = x.iter().fi var y = x.where y = x.select(&:p)
Create the list y (p) for _, v := range x{
lter(p).collect(); (p).toList();
filter returns an iterator. select is also aliased to find_all.
containing the items if p(v){
This collects into a vector (other
from the list x that satisfy Alternative implementation: y = append(y, v)
collections are possible)
the predicate p. Respect }

y = [element for element


the original ordering. }
in x if p(element)]
Don't modify x in-place.
List comprehensions tend to be For item type T.
more readable than filter Note that this allocates memory for the new slice y.

function Warning: y is allocated with as much memory as x,


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.



Python
Kotlin
Go
Rust
Dart
Ruby
58 Extract file content to a lines = open(f).read() import java.io.Fi import "io/ioutil" use std::io::prelude::*;
import "dart:io"; lines = File.read(f)
string le use std::fs::File;
For more complicated file b, err := ioutil.ReadFile(f)
var lines = new Fi Note that lines is a string here.
Create string lines from
operations, use a context File(f).readText if err != nil {
let mut file = File::open le(f).readAsString
the content of the file
manager with with () // Handle error...
(f)?;
Sync();
with filename f.
}
let mut lines = String::new Defaults to UTF-8
Alternative implementation:
lines := string(b) ();
encoding.

with open(f) as fo:


file.read_to_string(&mut li
In Go it is idiomatic to inspect an error value before To get lines directly,
lines = fo.read() nes)?;
moving on.
use:

The with statement creates a file.readAsLinesSync()


contextmanager, which lines is a single string. Alternative implementation:
automatically handles closing use std::fs;
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.
59 Write to standard error import sys System.err.printl import "os" eprintln!("{} is negative", import "dart:io"; warn "#{x} is negative"

stream n("$x is negativ x); $stderr.puts "%d is negative" %


Print the message "x is print(x, "is negative", f fmt.Fprintln(os.Stderr, x, "is negative") stderr.write("$x i
e")
x
negative" to standard ile=sys.stderr) s negative");
error (stderr), with Python3
integer x value
substitution (e.g. "-2 is Alternative implementation:
negative"). 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 import sys import "os" use std::env; main(args) {
x = ARGV.first
argument var x = args[0];

Assign to x the string x = sys.argv[1] x := os.Args[1] let first_arg = env::args


}
value of the first argv[0] is the program name os.Args[0] is actually the executable name. ().skip(1).next();

Command line
command line
let fallback = "".to_owned arguments are only
parameter, after the
();
available as argument
program name.
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.

Python
Kotlin
Go
Rust
Dart
Ruby
61 Get current date import datetime import "time" extern crate time; var d = DateTime.n d = Time.now
Assign to variable d the ow();

current date/time value, d = datetime.datetime.now d := time.Now() let d = time::now();


in the most standard () The type Time wraps a timestamp with The current time in the local
type. 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();

62 Find substring position i = x.find(y) import "strings" let i = x.find(y); var i = x.indexOf i = x.index(y)
Set i to the first position (y);
find returns the character i := strings.Index(x, y) i is an Option<usize>.
find returns the character index of y
of string y inside string x,
index of y in x, or -1 if not Finds the byte index of y in x in x, or nil if not found.
if exists.
i is the byte index of y in x, not the character
found. (not the character index).
(rune) index.

Specify if i should be
regarded as a character i will be -1 if y is not found in x.
index or as a byte index.

Explain the behavior


when y is not contained
in x.
63 Replace fragment of a x2 = x.replace(y, z) import "strings" let x2 = x.replace(&y, &z); var x2 = x.replace x2 = x.gsub(y, z)
string All(y, z);
x2 := strings.Replace(x, y, z, -1) Returns a string slice (&str). Add
Assign to x2 the value of
.to_string() or .to_owned() to
string x with all -1 means "no limit on the number of replacements".

get a String.
occurrences of y This replaces non-overlapping instances of y.
replaced by z.

Assume occurrences of
y are not overlapping.
64 Big integer : value 3 x = 3**247 import "math/big" extern crate num;
import "dart:mat x = 3 ** 247
power 247 use num::bigint::ToBigInt; h";
Assign to x the value x := new(big.Int)

3^247 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 s = '{:.1%}'.format(x) import "fmt" let s = format!("{:.1}%", 1 var s = "${(x * 10 s = "%.1f%%" % (100 * x)
number 00.0 * x); 0).toStringAsFixed
.1 means only one digit after s := fmt.Sprintf("%.1f%%", 100.0*x) Note that you need to use %%
From the real value x in (1)}%";

decimal point.
(double %) inside a format string to
[0,1], create its The literal % must be doubled.
% handles the "multiplication" produce a literal percent sign
percentage string
and shows the percentage
representation s with
sign.
one digit after decimal
point. E.g. 0.15625 -> Alternative implementation:
"15.6%"
s = f"{x:.01%}"

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

Python
Kotlin
Go
Rust
Dart
Ruby
67 Binomial coefficient "n import math import "math/big" extern crate num;
int binom(int n, i def binom(n,k)

choose k" nt k) {
(1+n-k..n).inject(:*)/(1..k).
Calculate binom(n, k) = def binom(n, k):
z := new(big.Int)

use num::bigint::BigInt;
int result = 1;
inject(:*)

n! / (k! * (n-k)!). Use an return math.factorial z.Binomial(n, k)


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

handle huge numbers. // math.factorial(n - k)


result = resul
fn binom(n: u64, k: u64) ->
t * (n - i) ~/ (i
Alternative implementation: BigInt {

+ 1);

import math let mut res = BigInt::o


}

ne();

def binom(n, k):


return r;

for i in 0..k {

return math.comb(n, }
res = (res * (n -
k) i).to_bigint().unwrap()) /

Python 3.8+ (i + 1).to_bi


gint().unwrap();

res

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

var x *big.Int = new(big.Int) Integers are promoted automatically


store n bits (n being import math
to hold (almost) any number of bits
potentially large). big.Int type makes a decent bitset.

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


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 import random import "math/rand" use rand::{Rng, SeedableRn import "dart:mat r = Random.new(s)
generator g, rngs::StdRng}; h";
Don't use system time to seed; not
Use seed s to initialize a rand = random.Random(s) rand.Seed(s)
let s = 32;
var r = new Random specifying s is far superior. (Docs: If
random generator.
this creates a new random s is of type int64.

let mut rng = StdRng::seed_ (s);


number is omitted, seeds the
generator rand This initializes the default Source.
from_u64(s); generator using a source of entropy
If s is constant, the
Alternative implementation: provided by the operating system, if
generator output will be
available (/dev/urandom on Unix
the same each time the import "math/rand"
systems or the RSA cryptographic
program runs. If s is
r := rand.New(rand.NewSource(s)) provider on Windows), which is then
based on the current
s is of type int64.
combined with the time, the process
value of the system
r is of type *rand.Rand. id, and a sequence number.)
clock, the generator
output will be different
each time.

Python
Kotlin
Go
Rust
Dart
Ruby
70 Use clock as random import random import "math/rand"
use rand::{Rng, SeedableRn var r = new Random Random.new
generator seed import "time" g, rngs::StdRng};
(new DateTime.now
rand = random.Random() Don't use time for seeding. Just use
Get the current datetime use std::time::SystemTime; ().millisecondsSin
rand.Seed(time.Now().UnixNano()) the initializer without any arguments.
and provide it as a seed the constructor uses the ceEpoch);
to a random generator. current time if used without This initializes the default Source. let d = SystemTime::now()

The generator sequence arguments.


.duration_since(SystemT
will be different at each you could also use the Alternative implementation: ime::UNIX_EPOCH)

run. functions of the random import "math/rand"


.expect("Duration since
module (they are using a import "time" UNIX_EPOCH failed");

shared ``Random`` object let mut rng = StdRng::seed_


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 import sys fun main(args: Ar import "fmt"
use std::env; main(List<String> printf("%s\n", ARGV.join(' '))
implementation ray<String>) = ar import "os"
args) {

Basic implementation of print ' '.join(sys.argv gs.forEach(::prin import "strings"


println!("{}", env::args().
print(args.join Alternative implementation:
the Echo program: Print [1:]) tln)
skip(1).collect::<Vec<_>>
(' '));

func main() {
().join(" ")); puts ARGV.join(' ')
all arguments except the }
program name, fmt.Println(strings.Join(os.Args[1:], "
separated by space, "))
Alternative implementation:
followed by newline.
} use itertools::Itertools;
The idiom demonstrates
println!("{}", std::env::ar
how to skip the first
gs().skip(1).format(" "));
argument if necessary,
concatenate arguments
as strings, append
newline and print it to
stdout.
73 Create a factory def fact(a_class, str_):
type ParentFactory func(string) Parent
def fact(klass, str)

Create a factory named if issubclass(a_clas klass.new(str) if klass.is_a?


fact for any sub class of s, Parent):
var fact ParentFactory = func(str string) P (Parent)

Parent and taking return a_class(st arent {


end
exactly one string str as r_) return Parent{

constructor parameter. 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 from fractions import gcd import "math/big" extern crate num;
int gcd(int a, int x = a.gcd(b)
Compute the greatest b) {

common divisor x of big x = gcd(a, b) x.GCD(nil, nil, a, b)


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

integers a and b. Use an The first two arguments can be ignored in this use use num::bigint::BigInt; var t = b;

integer type able to case.


b = a % t;

handle huge numbers. let x = a.gcd(&b);


a = t;

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

trait. return a;

}

Python
Kotlin
Go
Rust
Dart
Ruby
75 Compute LCM from math import gcd import "math/big" extern crate num;
x = lcm(a, b);
x = a.lcm(b)
Compute the least
common multiple x of big x = (a*b)//gcd(a, b) gcd.GCD(nil, nil, a, b)

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

handle huge numbers. 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 s = '{:b}'.format(x) import "strconv" let s = format!("{:b}", x); var s = x.toRadixS s = x.to_s(2)

integer tring(2);
s := strconv.FormatInt(x, 2) Formatting lets you choose
Create the string s of
another representation (e.g., `b`
integer x written in base Here x has the type int64.

for binary, `X` for hex in upper


2.

case and `_?` for debug output).


For very big numbers, prefer the type *big.Int.
E.g. 13 -> "1101"
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 = 3j-2
x := 3i - 2
extern crate num;
x = 3i - 2

Declare a complex x and y = x * 1j x *= 1i use num::Complex; x *= 1i


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

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

78 "do while" loop while True:


for{
loop {
do {
begin

Execute a block once, do_something()


someThing()
doStuff();
someThing();
# code

then execute it again as if not c:


someOtherThing()
if !c { break; }
someOtherThing end while c
long as boolean break if !c {
} ();

condition c is true. break


} while(c);
Rust has no do-while loop with
}
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.

Python
Kotlin
Go
Rust
Dart
Ruby
79 Convert integer to y = float(x) y := float64(x) let y = x as f32; double y = x.toDou y = x.to_f
floating point number ble();
The cast must be explicit.
Declare floating point
There is no implicit
number y and initialize it
conversion so you
with the value of integer
have to use toDouble
x.
explicitly, or maybe
better: type y as num
which is the
superclass of double
and int.
80 Truncate floating point y = int(x) y := int(x) let y = x as i32; int y = x.toInt() y = x.to_i
number to integer
There is no automatic Synonyms are truncate and to_int
Declare integer y and
conversion, so you
initialize it with the value
have to explicitly call
of floating point number
toInt on the double.
x . Ignore non-integer
The toInt call
digits of x .

truncates, there are


Make sure to truncate
also ceil, floor and
towards zero: a negative
round methods.
x must yield the closest
greater integer (not
lesser).
81 Round floating point y = int(x + 0.5) import "math" let y = x.round() as i64; var y = x.round();
y = (x + 1/2r).floor
number to integer
y := int(math.Floor(x + 0.5)) This rounds ties "away y = x.round_ rounds halves away
Declare integer y and
from zero", though. from zero. round_ takes a parameter
initialize it with the
to round halves toward zero, or
rounded value of floating
toward nearest even (bankers
point number x .

rounding), but not one to satisfy this


Ties (when the fractional
task.
part of x is exactly .5)
must be rounded up (to
positive infinity).
82 Count substring count = s.count(t) import "strings" let c = s.matches(t).count s.scan(t).size
occurrences ();
counts non-overlapping x := strings.Count(s, t) Overlapping occurrences will not be
Find how many times
occurrences Disjoint matches: overlapping counted.
string s contains Count counts only the number of non-overlapping
occurrences are not counted.
substring t.
instances of t.
Specify if overlapping
occurrences are
counted.
83 Regex with character import re import "regexp" extern crate regex;
r = /htt+p/
repetition use regex::Regex;
Declare regular r = re.compile(r"htt+p") r := regexp.MustCompile("htt+p")
expression r matching let r = Regex::new(r"htt+
strings "http", "htttp", p").unwrap();
"httttp", etc. In order to avoid compiling the
regex in every iteration of a loop,
put it in a lazy static or
something.

Python
Kotlin
Go
Rust
Dart
Ruby
84 Count bits set in c = bin(i).count("1") func PopCountUInt64(i uint64) (c int) {
let c = i.count_ones(); c = i.digits(2).count(1)
integer binary i -= (i >> 1) & 0x5555555555555555
i must have an explicit type, i.e.

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


Count number c of 1s in x3333333333333333

the integer i in base 2.


i += i >> 4

i &= 0x0f0f0f0f0f0f0f0f

E.g. i=6 → c=2 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 def adding_will_overflow import "math" fn adding_will_overflow(x: def addingWillOverflow(x,y)

addition will overflow (x,y):


usize, y: usize) -> bool {
false

Write boolean function func addingWillOverflow(x int, y int) bool


return False x.checked_add(y).is_non end
addingWillOverflow {

Python has arbitrary precision e()

which takes two integers if x > 0 {

integers so you shouldn't worry }


x, y and return true if return y > math.MaxInt-x

about overflow.
}
checked_add is available for all
(x+y) overflows.

Also, don't bother coding this return y < math.MinInt-x


integer types.
constant function! }
An overflow may be
above the max positive
value, or below the min
negative value.
86 Check if integer def multiplyWillOverflow func multiplyWillOverflow(x, y uint64) bool fn multiply_will_overflow def multiplyWillOverflow(x,y)

multiplication will (x,y):


{
(x: i64, y: i64) -> bool {
false

overflow return False if x <= 1 || y <= 1 {


x.checked_mul(y).is_non end
Write boolean function return false
e()

Python has arbitrary precision


multiplyWillOverflow }
}
integers so you shouldn't worry
which takes two integers d := x * y

about overflow.
checked_mul is available on all
x, y and return true if return d/y != x

Also, don't bother coding this integer types


(x*y) overflows.
}
constant function!
This holds for uint64, not for signed integers.

An overflow may be
Note that the multiplication is performed, then its
above the max positive
result is checked.
value, or below the min
negative value.

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

It is the caller's responsibility to check if the error is methodname and linenumber.


the current function is if x != 42 {

nil, before using the function's other result values.


invalid. Write the Err(CustomError::In
idiomatic way to abort validAnswer)

the function execution } else {

and signal the problem. 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.
90 Read-only outside class Foo(object):
type Foo struct {
struct Foo {
class Foo

Expose a read-only def __init__(self):


x int
x: usize

integer x to the outside self._x = 0


}
}
def initialize

world while being @x = rand(10)

writable inside a @property


func (f *Foo) X() int {
impl Foo {
end

structure or a class Foo. def x(self):


return f.x
pub fn new(x: usize) ->
"""
} Self {
def x

Doc for x
x is private, because it is not capitalized.
Foo { x }
@x

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

return self._x
pub fn x<'a>(&'a self) end

-> &'a usize {

&self.x

pub fn bar(&mut self) {

self.x += 1;

}

Python
Kotlin
Go
Rust
Dart
Ruby
91 Load JSON file into import json import "encoding/json"
#[macro_use] extern crate s import 'dart:io' s require 'json'
struct import "io/ioutil" erde_derive;
how File;

Read from file data.json with open("data.json", extern crate serde_json;


import 'dart:conve
x = JSON.parse(File.read('data.
and write its content into "r") as input:
buffer, err := ioutil.ReadFile("data.json")

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


json'))
object x.
x = json.load(input) if err != nil {

Assume the JSON data return err


let x = ::serde_json::from_ Map x = json.jsonD
is suitable for the type of }
reader(File::open("data.jso ecode(await new Fi
x. 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
92 Save object into JSON import json import "encoding/json"
extern crate serde_json;
import 'dart:io' s require "json"
file import "io/ioutil" #[macro_use] extern crate s how File;

Write the contents of the with open("data.json", erde_derive;


import 'dart:conve
x = {:hello => "goodbye"}

object x into the file "w") as output:


buffer, err := json.MarshalIndent(x, "", "
rt' show JSON;
data.json. json.dump(x, output) ")
File.open("data.json", "w") do
use std::fs::File;
if err != nil {
|f|

return err
::serde_json::to_writer(&Fi f.puts(x.to_json)

}
le::create("data.json")?, & end

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


0644) This requires x to implement
json.MarshalIndent is more human-readable than Deserialize from serde.
json.Marshal.

Python
Kotlin
Go
Rust
Dart
Ruby
class JsonModel {

// Create Field

int id;

String qrText, l
icen, trans, name;

// // 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 from __future__ import pr func control(f func()) {
fn control(f: impl Fn()) {
def control

procedure as int_function f()


f();
yield

parameter } } end
Implement procedure def control(f):

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


control which receives
functions, user-defined function types, function
one parameter f, and
literals, and closures.
runs f.

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

type.

do this in Kotlin. Alternative implementation: std::intrinsics::type_n


This may not make fmt.Printf("%T", x) ame::<T>()

sense in all languages. }

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 import "os" use std::fs; import 'dart:io'; x = File.size(path)
Assign to variable x the
length (number of bytes) x = os.path.getsize(path) info, err := os.Stat(path)
let x = fs::metadata(pat final x = (await F
Alternative implementation:
of the local file at path. if err != nil {
h)?.len(); ile(path).readAsBy
return err
tes()).length; def file_size(path)

}
Alternative implementation: "stat -f%z #{path}"

x := info.Size() Alternative end


let x = path.metadata()?.le
info has type os.FileInfo . n(); implementation: This issues a system command to
var x = File(pat find the file size.
path has type &std::path::Path
h).lengthSync();

96 Check string prefix b = s.startswith(prefix) val b = s.startsW import "strings" let b = s.starts_with(prefi var b = s.startsWi b = s.start_with?(prefix)
Set boolean b to true if ith(prefix) x); th(prefix);
string s starts with prefix b := strings.HasPrefix(s, prefix)
prefix, false otherwise.
97 Check string suffix b = s.endswith(suffix) b = s.endsWith(su import "strings" let b = s.ends_with(suffi var b = s.endsWith b = s.end_with?(suffix)
Set boolean b to true if ffix) x); (suffix);
string s ends with string b := strings.HasSuffix(s, suffix)
suffix, false otherwise.
98 Epoch seconds to date import datetime import "time" extern crate chrono;
var d = new DateTi require 'date'
object use chrono::prelude::*; me.fromMillisecond
Convert a timestamp ts d = datetime.date.fromtim d := time.Unix(ts, 0)
sSinceEpoch(ts, is
d = DateTime.strptime(ts, '%s')
(number of seconds in estamp(ts) ts has type int64.
let d = NaiveDateTime::from
Utc: true);
epoch-time) to a date The second argument is nanoseconds. _timestamp(ts, 0);
with time d. E.g. 0 ->
1970-01-01 00:00:00
99 Format date YYYY-MM- from datetime import date import "time" extern crate chrono;
import 'package:in require 'date'
DD use chrono::prelude::*; tl/intl.dart';
Assign to the string x the d = date(2016, 9, 28)
x := d.Format("2006-01-02") d = Date.today

value of the fields (year, x = d.strftime('%Y-%m-% d has type time.Time Utc::today().format("%Y-%m- x = DateFormat('YY x = d.to_s
month, day) of the date d') %d") YY-MM-DD').format
d, in format YYYY-MM- (d);
DD. Alternative implementation: Alternative implementation:
from datetime import date use time::macros::format_de
scription;
d = date.today()

x = d.isoformat() let format = format_descrip


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

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

Python
Kotlin
Go
Rust
Dart
Ruby
100 Sort by a comparator items.sort(key=c) items.sortWith(c) import "sort" items.sort_by(c); items.sort!{|a,b| a-b }
Sort elements of array-
c is a key function, see the type ItemCSorter []Item
sort! sorts in_place (sort would leave
like collection items,
doc. func (s ItemCSorter) Len() int { items unmodified). Comparator c is
using a comparator c.
return len(s) }
not idiomatic, items is sorted
Alternative implementation: according to the code in the block.
func (s ItemCSorter) Less(i, j int) bool {
import functools return c(s[i], s[j]) }

Alternative implementation:
items.sort(key=functools. func (s ItemCSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i] }
items.sort!(&c)
cmp_to_key(c))
Idiomatic would be using a block
c is an old-style comparison
func sortItems(items []Item) {
instead of named procedure c.
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.

Python
Kotlin
Go
Rust
Dart
Ruby
101 Load from HTTP GET import urllib.request
import "io/ioutil"
extern crate reqwest;
require 'net/http'

request into a string import "net/http" use reqwest::Client;


Make an HTTP request with urllib.request.urlop u = URI("http://example.com/ind
with method GET to URL en(u) as f:
res, err := http.Get(u)
let client = Client::new();
ex.html")

u, then store the body of s = f.read()


if err != nil {
let s = client.get(u).send s = Net::HTTP.get_response(u).b
the response in string s. return err
().and_then(|res| res.text ody

}
())?;
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.

Python
Kotlin
Go
Rust
Dart
Ruby
102 Load from HTTP GET import urllib import "fmt"
extern crate reqwest;
require 'net/http'
request into a file import "io"
use reqwest::Client;

Make an HTTP request filename, headers = urlli u = URI('http://example.com/lar


import "net/http" use std::fs::File;
with method GET to URL b.request.urlretrieve(u, ge_file')

u, then store the body of 'result.txt')


resp, err := http.Get(u)
let client = Client::new();

the response in file if err != nil {


match client.get(&u).send() Net::HTTP.start(u.host, u.port)
result.txt. Try to save return err
{
do |http|

the data as it arrives if }


Ok(res) => {
request = Net::HTTP::Get.new
possible, without having defer resp.Body.Close()
let file = File::cr (u)

all its content in memory if resp.StatusCode != 200 {


eate("result.txt")?;
http.request(request) do |res
at once. return fmt.Errorf("Status: %v", res ::std::io::copy(re ponse|

p.Status)
s, file)?;
open('result.txt', 'w') do
}
},
|file|

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


Err(e) => eprintln!("fa response.read_body do |ch
if err != nil {
iled to send request: {}", unk|

return err
e),
file.write(chunk)

}
}; end

defer out.Close()
end

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


end

if err != nil {
end
return err
The body is passed to the block,
} provided in fragments, as it is read in
resp has type *http.Response.
from the socket.
It is idiomatic and strongly recommended to check
errors at each step, except for the calls to Close.
103 Load XML file into import lxml.etree import "encoding/xml"

struct import "io/ioutil"


Read from the file x = lxml.etree.parse('dat
data.xml and write its a.xml') buffer, err := ioutil.ReadFile("data.xml")

contents into the object Use "pip install" to get this if err != nil {

x.
third-party library. It's industry return err

Assume the XML data is standard for python xml. }

suitable for the type of x. 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 import "encoding/xml"

file import "io/ioutil"


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

if err != nil {

return err

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


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

Python
Kotlin
Go
Rust
Dart
Ruby
105 Current executable import sys import "os"
fn get_exec_name() -> Optio s = __FILE__
name import "path/filepath" n<String> {

Assign to string s the s = sys.argv[0]


std::env::current_exe()
Alternative implementation:
name of the currently sys.argv[0] holds the name of path := os.Args[0]

.ok()
s = $0
executing program (but the currently running script, you s = filepath.Base(path)
.and_then(|pb| pb.f
not its full path). might use __file__, but if called The program path is its "0th argument". Unfortunately, s includes the path
ile_name().map(|s| s.to_os_
from within a module you given to the interpreter, not just the
string()))

would then get the module's .rb program name.


.and_then(|s| s.int
__file__ attribute. o_string().ok())

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

Assign to string dir the dir = os.path.dirname(os.


.canonicalize()

path of the folder path.abspath(__file__)) programPath := os.Args[0]

.expect("the current ex
containing the currently absolutePath, err := filepath.Abs(programPa
e should exist")

running executable.
th)

.parent()

(This is not necessarily if err != nil {

.expect("the current ex
the working directory, return err

e should be a file")

though.) }

.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 �

Python
Kotlin
Go
Rust
Dart
Ruby
108 Determine if variable if 'x' in locals():
puts x if defined?(x)
name is defined print x
Print the value of
variable name must be quoted.
variable x, but only if x
has been declared in this Alternative implementation:
program.

try:

This makes sense in


x

some languages, not all


except NameError:

of them. (Null values are


print("does not exis
not the point, rather the
t")
very existence of the
variable.)
109 Number of bytes of a import pympler.asizeof import "reflect" let n = ::std::mem::size_o require 'objspace'
type f::<T>();
Set n to the number of n = pympler.asizeof.asize var t T
n = ObjectSpace.memsize_of(t)
of(t) tType := reflect.TypeOf(t)
n is "the offset in bytes between
bytes of a variable t (of From the docs: " Generally, you
n := tType.Size() successive elements in an array
type T). `pip install pympler` to get this *SHOULD NOT* use this library if you
with item type T"
third-party library. This run-time reflection works on a value of the do not know about the MRI
`sys.getsizeof` is built-in, but type T.
implementation. Mainly, this library is
has many common failure Note that the size does not include the memory for (memory) profiler developers and
modes. indirectly taken by the reference fields: Strings, MRI developers who need to know
slices, etc.
about MRI memory usage."
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 blank = s is None or s.st val blank = s.isN import "strings" let blank = s.trim().is_emp final blank = s == blank = s.strip.empty?
Set the boolean blank to rip() == '' ullOrBlank() ty(); null || s.trim() =
true if the string s is blank := strings.TrimSpace(s) == ""
= '';
empty, or null, or Trim s, then check if empty.
contains only whitespace Alternative
; false otherwise. implementation:
bool blank = s?.tr
im()?.isEmpty ?? t
rue;
? -> null safe check
?? -> on null

Python
Kotlin
Go
Rust
Dart
Ruby
111 Launch other program import subprocess import "os/exec" use std::process::Command; `x a b`
From current process,
subprocess.call(['x', err := exec.Command("x", "a", "b").Run() let output = Command::new The `'s are backticks, not apostrophes
run program x with
'a', 'b']) ("x")
( ').
command-line x's output is ignored.

parameters "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 for k in sorted(mymap):
import "fmt"
for (k, x) in mymap {
my_map.sort.each{|k,x| puts "#
entries, ordered by print(mymap[k])
import "sort" println!("({}, {})", k, {k}: #{x}"}
keys x);

dictionaries iterate over their keys := make([]string, 0, len(mymap))

Print each key k with its }


keys by default for k := range mymap {

value x from an
keys = append(keys, k)
This assumes mymap is a
associative array
}
BTreeMap as it is sorted by the
mymap, in ascending
sort.Strings(keys)
keys.
order of k.

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 for x, k in sorted((x, k) import "fmt"
use itertools::Itertools; h.sort_by{|k,x| x}.each{|k,x| p
entries, ordered by for k,x in mymap.items import "sort" uts "#{k}: #{x}"}
values ()):

Print each key k with its print(k, x)

value x from an
Alternative implementation:

Python
Kotlin
Go
Rust
Dart
Ruby
associative array import operator type entry struct {
for (k, x) in mymap.iter().
mymap, in ascending key string
sorted_by_key(|x| x.1) {

for key, value in sorted


order of x.
value int
println!("[{},{}]",
(d.items(), key=operator.
Note that multiple entries }
k, x);

itemgetter(1)):

may exist for the same }


print(key, value)
value x. type entries []entry

operator.itemgetter(1) gets the Requires the itertools crate


func (list entries) Len() int { return len
second item in the tuple
(list) }
Alternative implementation:
returned by d.items()
func (list entries) Less(i, j int) bool { r let mut items: Vec<_> = mym
eturn list[i].value < list[j].value }
ap.iter().collect();

func (list entries) Swap(i, j int) { list items.sort_by_key(|item| it


[i], list[j] = list[j], list[i] }
em.1);

for (k, x) in items {

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


println!("[{},{}]", k,
for k, x := range mymap {
x);

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)

}
Using sort.Slice incurs slightly less boilerplate than
sort.Sort.

Python
Kotlin
Go
Rust
Dart
Ruby
114 Test deep equality b = x == y import "reflect" let b = x == y; b = x == y

Set boolean b to true if


The classes of x and y need to b := reflect.DeepEqual(x, y) The == operator can only be x and y may contain themselves!
objects x and y contain
delegate to any contained used by having a type
the same values, This uses run-time reflection.

objects' _eq__ implementation.


implement PartialEq.
recursively comparing all DeepEqual correctly handles recursive types.
All objects in the standard
referenced elements in x
library do so.
and y.

Tell if the code correctly


handles recursive types.
115 Compare dates import datetime import "time" extern crate chrono;
b = d1 < d2
Set boolean b to true if use chrono::prelude::*;
date d1 is strictly before b = d1 < d2 b := d1.Before(d2)
date d2 ; false d1, d2 have type date d1, d2 have type time.Time. let b = d1 < d2;
otherwise.
116 Remove occurrences s2 = s1.replace(w, '') import "strings" s2 = s1.replace(w, ""); s2 = s1.gsub(w, "")
of word from string
Remove all occurrences s2 := strings.Replace(s1, w, "", -1)

Alternative implementation:
of string w from string Replaces w with empty string. -1 means "replace
let s2 = str::replace(s1,
s1, and store the result all occurrences".
w, "");
in s2.
Alternative implementation:
import "strings"

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

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

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


use std::collections::HashS var y = x.toSet(); require 'set'
Create set y from list x.
for _, v := range x {
et;
List<T> has a method y = x.to_set
x may contain y[v] = struct{}{}

let y: HashSet<_> = x.into_ to convert directly to


duplicates. y is }
iter().collect(); Set<T>.
unordered and has no
Iterate to add each item to the map.

repeated values.
T is the type of the items.

Python
Kotlin
Go
Rust
Dart
Ruby
119 Deduplicate list x = list(set(x)) x = x.toSet().toL y := make(map[T]struct{}, len(x))
x.sort();
x = x.toSet().toLi x.uniq!
Remove duplicates from ist() for _, v := range x {
x.dedup(); st();
Doesn't preserve order
the list x. y[v] = struct{}{}

original ordering is Deduplication in place. Original


Explain if the original Alternative implementation: }

not preserved order not maintained. Works


order is preserved. x2 := make([]T, 0, len(y))

from collections import O O(n*log(n))


rderedDict Alternative for _, v := range x {

implementation: if _, ok := y[v]; ok {
Alternative implementation:
x = list(OrderedDict(zip x2 = append(x2, v)
x = x.distinct() use itertools::Itertools;
(x, x))) delete(y, v)

Ordering is let dedup: Vec<_> = x.iter


Preserves order }

preserved ().unique().collect();
}

x = x2
Original order is preserved.

T is the type of the items.

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

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).

Python
Kotlin
Go
Rust
Dart
Ruby
120 Read integer from n = int(input("Input Prom import "fmt" fn get_input() -> String {
n = $stdin.gets.to_i
stdin pting String: ")) let mut buffer = Strin
_, err := fmt.Scan(&n) gets is Kernel.gets which may not
Read an integer value g::new();
always be stdin. Here we refer
from the standard input Warning: if the input has a leading 0, it will be std::io::stdin().read_l explicitly to stdin.
into the variable n 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();
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



Python
Kotlin
Go
Rust
Dart
Ruby
121 UDP listen and read import socket import (
use std::net::UdpSocket; require 'socket'
Listen UDP traffic on "fmt"

port p and read 1024 sock = socket.socket(sock let mut b = [0 as u8; 102 require 'socket'

"net"

bytes into buffer b. et.AF_INET, socket.SOCK_D 4];

"os"

GRAM)
let sock = UdpSocket::bind p = 4913

)
sock.bind((UDP_IP, p))
(("localhost", p)).unwrap u1 = UDPSocket.new

while True:
ServerAddr,err := net.ResolveUDPAddr("udp", ();
u1.bind("127.0.0.1", p)

data, addr = sock.rec p)


sock.recv_from(&mut b).unwr u1.send "message-to-self", 0,
vfrom(1024)
if err != nil {
ap(); "127.0.0.1", p

print("received messa return err

ge:", data) }
b = u1.recvfrom(1024).first
Buffer size is 1024 bytes ServerConn, err := net.ListenUDP("udp", Ser
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 class Suit:


type Suit int
enum Suit {
enum Suit {
require 'ruby-enum'
Create an enumerated SPADES, HEARTS, D Spades,
SPADES,

type Suit with 4 possible class Colors

IAMONDS, CLUBS = range(4) const (


Hearts,
HEARTS,

values SPADES, include Ruby::Enum

Fake enum, works with any Spades Suit = iota


Diamonds,
DIAMONDS,

HEARTS, DIAMONDS, Hearts


Clubs,
CLUBS,

version of python. define :SPADES, "spades"

CLUBS. Diamonds
} }
define :HEARTS, "hearts"

Alternative implementation: Clubs

define :DIAMONDS, "diamonds"

from enum import Enum )


define :CLUBS, "clubs"

Go doesn't have enumerations.


end
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
123 Assert condition assert isConsistent if !isConsistent() {
assert!(is_consistent); assert(isConsisten raise unless isConsistent
Verify that predicate panic("State consistency violated")
t)
raises AssertionError There's no assert method in Ruby
isConsistent returns }
Exception.
Needs to be executed standard library
true, otherwise report
Go doesn't provide assertions.
with "--enable-asserts"
assertion violation.

Running Python with option _- But it's still possible to crash when desired. flag with dart and
Explain if the assertion is
O or with PYTHONOPTIMZE
dart2js commands.

executed even in
environment variable In Flutter it will
production environment
suppresses all asserts. execute only in debug
or not.
mode.

dartdevc
(development
compiler) will execute
it by default.

Python
Kotlin
Go
Rust
Dart
Ruby
124 Binary search for a import bisect func binarySearch(a []T, x T) int {
a.binary_search(&x).unwrap_ def binarySearch(a def binary_search(a, el)

value in sorted array imin, imax := 0, len(a)-1


or(-1); r, el)
a.bsearch_index{|x| x == el}
Write the function def binarySearch(a, x):

for imin <= imax {


This only works if a is an array of res = ar.bsearch || -1

binarySearch which i = bisect.bisect_lef


imid := imin + (imax-imin) signed integers.
{|x| x == el}
end
returns the index of an t(a, x)

/ 2
Generally, a Result or Option res ? res : -1
Returning -1 is required, however
element having the value return i if i != len
switch {
would be more useful. end index -1 refers to the last element of
x in the sorted array a, (a) and a[i] == x else -1

case a[imid] == x: an array. More idiomatic is returning


or -1 if no such element return imid
nil (which bsearch_index does).
exists. 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.



Python
Kotlin
Go
Rust
Dart
Ruby
125 Measure function call import time import "time" use std::time::{Duration, I t1 = Time.now

duration nstant}; foo

measure the duration t, t1 = time.perf_counter_ns t1 := time.Now()

p (Time.now - t1)*1000000
in nanoseconds, of a call ()
foo()
let start = Instant::now();

to the function foo. Print foo()


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

this duration. t2 = time.perf_counter_ns ns := int64(t / time.Nanosecond)


let duration = start.elapse
()
fmt.Printf("%dns\n", ns) d();

print('Nanoseconds:', t2 t1 has type time.Time.


println!("{}", duration);

- t1) t has type time.Duration.


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 def foo():
fun foo() : Pair< func foo() (string, bool) {
fn foo() -> (String, bool) def foo

Write a function foo that return 'string', True


String, Boolean> return "Too good to be", true
{
string, boolean = "bar", fal
returns a string and a = Pair(5, true)
} (String::from("bar"), t se

boolean value. rue)


[string, boolean]

fun useFoo() {
} end
val a, b = foo
()

127 Source code inclusion import imp fn main() {


def foo

Import the source code include!("foobody.tx eval File.read "foobody.txt"

for the function foo body foo = imp.load_module('fo t");


end

from a file "foobody.txt" . obody', 'foobody.txt').fo }


File foobody.txt will be read and
The declaration must not o
"foobody.txt" must contain a evaluated at runtime.

reside in the external file. To remove all side-effects: del


single Rust expression. If you Using eval will make the final value of
sys.modules['foobody']
need several, enclose them in foobody.txt available to be returned by
braces. foo.

Using load or require will not.



Python
Kotlin
Go
Rust
Dart
Ruby
128 Breadth-first traversing def BFS(f, root):
func (root *Tree) Bfs(f func(*Tree)) {
use std::collections::VecDe
of a tree Q = [root]
if root == nil {
que;
Call a function f on every while Q:
return

node of a tree, in struct Tree<V> {

n = Q.pop }

breadth-first prefix order children: Vec<Tree<V>>,

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

value: V

f(n)
for len(queue) > 0 {

for child t := queue[0]

in n:
queue = queue[1:]

impl<V> Tree<V> {

i f(t)

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

ldren...)

let mut q = VecDequ


n.discovered = True
}

e::new();

}
q.push_back(self);

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


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 from collections import d func (start *Vertex) Bfs(f func(*Vertex)) {
use std::rc::{Rc, Weak};

in a graph eque queue := []*Vertex{start}


use std::cell::RefCell;
Call the function f on seen := map[*Vertex]bool{start: tru
every vertex accessible def breadth_first(start,
e}

from the vertex start, in f):

for len(queue) > 0 {

breadth-first prefix order 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)

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


Python when the structure size = true

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.

Python
Kotlin
Go
Rust
Dart
Ruby

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.



Python
Kotlin
Go
Rust
Dart
Ruby
130 Depth-first traversing def depth_first(start, func (v *Vertex) Dfs(f func(*Vertex), seen use std::rc::{Rc, Weak};

in a graph f):
map[*Vertex]bool) {
use std::cell::RefCell;
Call a function f on every seen = set()
seen[v] = true

vertex accessible for struct Vertex<V> {

stack = [start]
f(v)

vertex v, in depth-first value: V,

while stack:
for next, isEdge := range v.Neighbo
prefix order neighbours: Vec<Wea
vertex = stack.pop()
urs {

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

f(vertex)
if isEdge && !seen[next] {

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

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
It's best to not recurse in start node.
Fn(&V), s: &mut Vec<*const
Python when the structure size The function f is a parameter of the traversal Vertex<V>>) {

is unknown, since we have a method.


s.push(start.as_ptr
fixed, small stack size. Start with an empty map as initial seen parameter. ());

(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.


131 Successive conditions f1 if c1 else f2 if c2 el switch {
if c1 { f1() } else if c2 { if (c1) {
case

Execute f1 if condition se f3 if c3 else None case c1:


f2() } else if c3 { f3() } f1;
when c1

c1 is true, or else f2 if when {

f1()
Using if and else } else if (c2) {
f1

condition c2 is true, or c1 -> f1

Alternative implementation: case c2:


f2;
when c2

else f3 if condition c3 is c2 -> f2

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

true. c3 -> f3

f1()
case c3:
match true {
f3;
when c3

Don't evaluate a }
elif c2:
f3()
_ if c1 => f1(),
} f3

condition when a } end


f2()
_ if c2 => f2(),

previous condition was


elif c3:
_ if c3 => f3(),

true.
f3() _ => (),

}
Using match and guards

Python
Kotlin
Go
Rust
Dart
Ruby
132 Measure duration of import timeit import "time" use std::time::Instant; def clock

procedure execution t = Time.now

Run procedure f, and duration = timeit.timeit func clock(f func()) time.Duration {


let start = Instant::now();

yield

return the duration of the ("f()", setup="from __mai t := time.Now()


f();

Time.now - t

execution of f. n__ import f") f()


let duration = start.elapse
end

Setup makes the function f return time.Since(t)


d();
accessible to timeit. Returned } duration is a std::time::Duration, clock{ f }

is the execution time in You may use this clock function to time any piece which can be converted into
seconds of code, by wrapping the code in a closure of type seconds with as_secs()
func().
Alternative implementation:
import time

start = time.time()

f()

end = time.time()

return end - start

This returns the duration in


seconds.
133 Case-insensitive string ok = word.lower() in s.lo import "strings" extern crate regex;
ok = s.match?( /#{word}/i )
contains wer() use regex::Regex;
lowerS, lowerWord := strings.ToLower(s), st Regular expressions can be
Set boolean ok to true if
rings.ToLower(word)
let re = Regex::new(&forma interpolated. The i means case-
string word is contained
ok := strings.Contains(lowerS, lowerWord) t!("(?i){}", regex::escape insensitive.
in string s as a substring,
even if the case doesn't Package strings has no case-insensitive version of (word))).unwrap();

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


otherwise. 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 = [a, b, c] val l = listOf(_ items := []T{a, b, c} let items = vec![a, b, c]; var items = [a, b, items = [a, b, c]
Declare and initialize a a,_b,_c) c];
This creates a slice of type T.
new list items,
containing 3 elements a,
b, c.

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

by its value if y == x {
t(&x) {
items.delete_at(i) unless i.ni
Raises a ValueError if x is not
Remove at most 1 item items = append(items[:i], i items.remove(i);
l?
found.
from list items, having tems[i+1:]...)
}
value x. break

This will alter the original }

list or return a new list, }


depending on which is
First find a matching index i. Then remove at
more idiomatic.

position i.

If there are several


occurrences of x in
Warning: you may have a memory leak at the last
items, remove only one
element of the original list, if the items have a
of them. If x is absent,
pointer type.
keep items unchanged.
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.

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

items.
} Alternative implementation:
This will alter the original
This is simple and runs in linear time.
items.retain(|&item| item !
list or return a new list,
However, it allocates memory for the new slice = x);
depending on which is
items2.
items has type Vec.

more idiomatic.
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.

Python
Kotlin
Go
Rust
Dart
Ruby
137 Check if string b = s.isdigit()
b := true
let chars_are_numeric: Vec< final b = RegExp b = s.count("^0-9").zero?
contains only digits for _, c := range s {
bool> = s.chars()
(r'^[0-9]+$').hasM
Here digits are characters
Set boolean b to true if if c < '0' || c > '9' {
atch(s);
having Numeric_Type=Digit or
string s contains only b = false
.map(|c|c.is_numeric())

Numeric_Type=Decimal, this
characters in range break

is not exactly the range '0'..'9'.

'0'..'9', false otherwise. }


.collect();

Returns false if s is empty.


} let b = !chars_are_numeric.

c has type rune. contains(&false);

Note that is_numeric is not just


Alternative implementation: 0 -> 9.
import "strings" See documentation for more
info.
isNotDigit := func(c rune) bool { return c
< '0' || c > '9' }
Alternative implementation:
b := strings.IndexFunc(s, isNotDigit) == -1
let b = s.chars().all(cha
r::is_numeric);

Alternative implementation:
let b = s.bytes().all(|c|
c.is_ascii_digit());

only return true for ASCII digits


138 Create temp file import tempfile import "io/ioutil" use tempdir::TempDir;
require 'tempfile'
Create a new temporary use std::fs::File;
file on the filesystem. file = tempfile.Temporary tmpfile, err := ioutil.TempFile("", "") file = Tempfile.new('foo')
File() tmpfile has type *os.File.
let temp_dir = TempDir::new A unique filename in tmpdir , e.g.:
("prefix")?;
"/tmp/foo.24722.0"
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 tempfile import "io/ioutil" extern crate tempdir;
require 'tmpdir'
Create a new temporary use tempdir::TempDir;
folder on filesystem, for td = tempfile.TemporaryDi dir, err := ioutil.TempDir("", "") td = Dir.mktmpdir
writing. rectory() dir is a string.
let tmp = TempDir::new("pre

tempfile.TemporaryDirectory() fix")?;
was added in Python 3.2 .
Consider defer os.RemoveAll(dir) for cleanup.
It wraps lower-level function
mkdtemp() .
140 Delete map entry m.pop(k, None) delete(m, k) use std::collections::HashM Map myMap = {};
m.delete(k)
Delete from map m the ap; myMap.remove(key)
A missing key will leave the delete is a built-in function.
returns nil if k is absent
entry having key k.

map unchanged.
m.remove(&k); Removes from
It's safe even if k is already absent from m.
Explain what happens if Returns the value at the key if
If the second parameter is
k is not an existing key the key was previously in the
omitted, a missing key will
in m. map, and 'None' otherwise.
raise the exception KeyError

Python
Kotlin
Go
Rust
Dart
Ruby
141 Iterate in sequence for x in items1 + items2:
for _, v := range items1 {
for i in item1.iter().chain [items1, items2].each{|ar| ar.e
over two lists print(x)
fmt.Println(v)
(item2.iter()) {
ach{|item| p item }}
Iterate in sequence over }
print!("{} ", i);

the elements of the list for _, v := range items2 {


} Alternative implementation:
items1 then items2. For fmt.Println(v)
items1.chain(items2).each{|item
each iteration print the } | puts item}
element.
No magic sugar. Write 2 loops. chain is added to Ruby in version 2.6
142 Hexadecimal digits of s = hex(x) import "strconv" let s = format!("{:X}", x); s = x.to_s(16)
an integer
s := strconv.FormatInt(x, 16) {:X} produces uppercase hex.

Assign to string s the


{:x} produces lowercase hex.
hexadecimal
representation (base 16) Alternative implementation:
of integer x.
import "fmt"

import "math/big"
E.g. 999 -> "3e7"
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.
143 Iterate alternatively for pair in zip(item1, it for i := 0; i < len(items1) || i < len(item extern crate itertools; items1.zip(items2){|pair| puts
over two lists em2): print(pair) s2); i++ {
pair}
Iterate alternatively over for pair in izip!(&items1,
This will print former if i < len(items1) {
There will be as much pairs as there
the elements of the list &items2) {

min(len(item1), item(2)) pairs if fmt.Println(items1[i])


are items in items1. items2 will be
items1 and items2. For println!("{}", pair.0);

len(item1) != len(item2). }
"padded" with nils or trimmed as
each iteration, print the println!("{}", pair.1);

if i < len(items2) {
needed.
element.
}
fmt.Println(items2[i])

Explain what happens if }


items1 and items2 have
different size.
144 Check if file exists import os import java.io.Fi import "os" let b = std::path::Path::ne b = File.exist?(fp)
Set boolean b to true if le; w(fp).exists();

file at path fp exists on b = os.path.exists(fp) _, err := os.Stat(fp)

filesystem; false b = File(fb).exis b := !os.IsNotExist(err)


otherwise.
Alternative implementation: ts() There's no specific existence check func in
from pathlib import Path standard library, so we have to inspect an error
Beware that you should return value.
b = Path(fp).exists()
never do this and then in
the next instruction
assume the result is still
valid, this is a race
condition on any
multitasking OS.

Python
Kotlin
Go
Rust
Dart
Ruby
145 Print log line with import sys, logging import "log" eprintln!("[{}] {}", humant require 'logger'
datetime ime::format_rfc3339_seconds
Print message msg, logging.basicConfig(strea log.Println(msg) logger = Logger.new('logfile.lo
(std::time::SystemTime::now
prepended by current m=sys.stdout, level=loggi This prints to os.Stderr by default, with a datetime g') #or STDOUT or STDERR

()), msg);
date and time.
ng.DEBUG, format="%(ascti prefix. logger.info(msg)
me)-15s %(message)s")
Writes an RFC3339 date to
Default Log format:

stderr with the message


Explain what behavior is logger = logging.getLogge
idiomatic: to stdout or r('NAME OF LOGGER')
SeverityID, [DateTime #pid]
stderr, and what the SeverityLabel -- ProgName: message

date format is. logger.info(msg)

Default output is stderr.


The default can be customized, as
well as the datetime format.
Date format is ISO 8601.
146 Convert string to import locale import "strconv" let f = s.parse::<f32>().un f = num.parse(s); f = s.to_f
floating point number wrap();
s = u'545,2222'
f, err := strconv.ParseFloat(s, 64) This method never raises an
Extract floating point
locale.setlocale(locale.L exception.
value f from its string f has type float64. Alternative implementation:
representation s C_ALL, 'de')

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


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)

147 Remove all non-ASCII import re import "regexp" let t = s.replace(|c: char| t = s.gsub(/[^[:ascii:]]/, "")
characters !c.is_ascii(), "");
Create string t from t = re.sub('[^\u0000-\u00 re := regexp.MustCompile("[[:^ascii:]]")

Alternative implementation:
string s, keeping only 7f]', '', s) t := re.ReplaceAllLiteralString(s, "")
Alternative implementation: t = s.gsub(/[[:^ascii:]]/, "")
ASCII characters
Alternative implementation: Alternative implementation: let t = s.chars().filter(|c
| c.is_ascii()).collect::<S
t = s.encode("ascii", "ig import (

tring>();
nore").decode() "fmt"

"strings"

"unicode"

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

if r > unicode.MaxASCII {

return -1

return r

}, s)

Python
Kotlin
Go
Rust
Dart
Ruby
148 Read list of integers list(map(int, input().spl import (
use std::{
STDIN.read.split.map(&:to_i)
from stdin it()) "bufio"
io::{self, Read},

split will split the input around spaces


Read a list of integer "os"
str::FromStr,

by default.

numbers from the Alternative implementation: "strconv"


}
standard input, until )
numbers = [int(x) for x i let mut string = String::ne map(&:to_i) is just short for the block
EOF.
n input().split()] var ints []int
w();
map{|x| x.to_i}
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 p = p.rstrip("/") import "strings" if p.ends_with('/') { p.pop p.chomp!("/")
Remove last character (); }
If there are several trailing p = strings.TrimSuffix(p, "/") chomp! modifies string p in-place.
from string p, if this
slashes, rstrip will remove all p has type String
character is a slash /. Alternative implementation:
of them
p = p.chomp("/")

chomp returns a new string.


151 Remove string trailing import os import "fmt"
let p = if ::std::path::is_ p.chomp!("/")
path separator import "os"
separator(p.chars().last().
if p.endswith(os.sep):
Ruby uses / as path separator on all
Remove last character import "strings" unwrap()) {

p = p[:-1] platforms, including windows.


from string p, if this &p[0..p.len()-1]

character is the file path sep := fmt.Sprintf("%c", os.PathSeparator)

} else {

separator of current p = strings.TrimSuffix(p, sep)


p

platform.
os.PathSeparator is a rune, it must be converted };
to string.
Note that this also Alternative implementation:
transforms unix root path Alternative implementation:
p = p.strip_suffix(std::pat
"/" into the empty string! 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 s = c val c: Char = 'c'
import "fmt" let s = c.to_string(); s = ?c
string val s: String =
a character is a single s := fmt.Sprintf("%c", c) s = "c" is fine too
Create string s c.toString()
character string, not a distinct
containing only the
datataype
character c.

Python
Kotlin
Go
Rust
Dart
Ruby
153 Concatenate string t = '{}{}'.format(s,i) import "fmt" let t = format!("{}{}", s, t = s + i.to_s
with integer i);
Create string t as the t := fmt.Sprintf("%s%d", s, i)
Alternative implementation:
concatenation of string s
t = f'{s}{i}' Alternative implementation:
and integer i.
the 'f' in front of the string import "strconv"
makes it a Literal String, in
t := s + strconv.Itoa(i)
which you can put expressions
inside brackets This is faster than fmt.Sprintf.
154 Halfway between two r1, g1, b1 = [int(c1[p:p+ import "fmt"
use std::str::FromStr;
rgbs = c1[1..-1].scan(/../), c2
hex color codes 2], 16) for p in range(1, import "strconv" use std::fmt; [1..-1].scan(/../)

Find color c, the average 6,2)]


c = "#%02X%02X%02X" % rgbs.tran
between colors c1, c2.
r1, _ := strconv.ParseInt(c1[1:3], 16, 0)
"Too long for text box, see
r2, g2, b2 = [int(c2[p:p+ spose.map{|h1, h2| (h1.hex + h
r2, _ := strconv.ParseInt(c2[1:3], 16, 0)
online demo"
2], 16) for p in range(1, 2.hex)/2 }
c, c1, c2 are strings of r := (r1 + r2) / 2

6,2)]

hex color codes: 7 chars, c = '#{:02x}{:02x}{:02


beginning with a number x}'.format((r1+r2) // 2, g1, _ := strconv.ParseInt(c1[3:5], 16, 0)

sign # .
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)

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


Assume linear g := (g1 + g2) / 2

computations, ignore Alternative implementation:


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

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

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

@classmethod

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

r):
For conciseness this assumes that input validity
return numpy.array([
has already been checked, so we omit some
int(rgbstr[i:i+2], returned errors.
16)

for i in range(1, l Alternative implementation:


en(rgbstr), 2)
import "fmt"

]).view(cls)
import "strconv"

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[:])

print((c1 + c2) / 2) Loops over each component r, g, b.

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.

Python
Kotlin
Go
Rust
Dart
Ruby
155 Delete file import pathlib import "os" use std::fs; File.delete(filepath)
Delete from filesystem
path = pathlib.Path(_file err := os.Remove(filepath) let r = fs::remove_file(fil Raises an exception on any error.
the file having path
filepath. path)
epath);
path.unlink() r has type io::Result<()>
156 Format integer with s = format(i, '03d') import "fmt" let s = format!("{:03}", s = "%03d" % i
zero-padding i);
Assign to string s the s := fmt.Sprintf("%03d", i)
value of integer i in 3 Flag 0 means "pad with zeroes, not with spaces".

decimal digits. Pad with Flag 3 is the width.


zeros if i < 100. Keep all
digits if i ≥ 1000.
157 Declare constant string PLANET = 'Earth' const val planet: const planet = "Earth" const PLANET: &str = "Eart const String _plan Planet = 'Earth'
Initialize a constant String = "Earth" h"; et = "Earth";
Names of constants are by Type string is inferred. Constants start with a capital.
planet with string value
convention written in
"Earth".
uppercase
158 Random sublist import random import "math/rand" use rand::prelude::*; y = x.sample(k)
Create a new list y from
The original ordering is not preserved.
randomly picking exactly y = random.sample(x, k) y := make([]T, k)
let mut rng = &mut rand::th
k elements from list x.
The original ordering is not perm := rand.Perm(len(x))
read_rng();

preserved. for i, v := range perm[:k] {


let y = x.choose_multiple(&
It is assumed that x has y[i] = x[v]
mut rng, k).cloned().collec
at least k elements.
} t::<Vec<_>>();
Each element must have Allocate a slice of T of size exactly k.
choose_multiple returns an
same probability to be perm is a slice of int of size len(x).
Iterator.
picked.
This is O(len(x)) in space and runtime.

Each element from x


must be picked at most The original ordering is not preserved.
once.

Explain if the original


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

Define a Trie data def __init__(self, pre c rune


val: String,

structure, where entries fix, value=None):


children map[rune]*Trie
nodes: Vec<Trie>

have an associated self.prefix = pref isEntry bool


}
value.
ix
value V

(Not all nodes are self.children = []


}
entries) self.value = value Using type rune, multi-byte characters are correctly
handled.

V is the type of the associated values.


160 Detect if 32-bit or 64-bit import sys import "strconv" match std::mem::size_of::<& case 1.size

architecture char>() {
when 8 then f64

Execute f32() if platform if sys.maxsize > 2**32:


if strconv.IntSize==32 {

4 => f32(),
when 4 then f32

is 32-bit, or f64() if f64()


f32()

8 => f64(),
end
platform is 64-bit.
else:
}

_ => {}

This can be either a f32()


if strconv.IntSize==64 {

}
compile-time condition f64()

} Performed at run time.


(depending on target) or runtime check
a runtime detection.

Python
Kotlin
Go
Rust
Dart
Ruby
161 Multiply all the elements = [c * x for x i for i := range elements {
let elements = elements.int elements = [for (v elements.map { |el| el * c }
elements of a list n elements] elements[i] *= c
o_iter().map(|x| c * x).col ar e in elements) Constants start with a capital, so c
Multiply all the elements } lect::<Vec<_>>(); e * c];
This maps the lambda function would be C
of the list elements by a
that multiplies a number by c to It is idiomatic to write this explicit loop. From Dart 2.3, using
constant c Alternative implementation:
the list elements , and collection for
overwrites the old list elements.iter_mut().for_eac
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 import sys import "flag" if let Some(arg) = ::std::e bat if ARGV.include?("b")

depending on options nv::args().nth(1) {


fox if ARGV.include?("f")
execute bat if b is a if 'b' in sys.argv[1:]: b var b = flag.Bool("b", false, "Do bat")

if &arg == "f" {

program option and fox at()


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

fox();

if f is a program option. if 'f' in sys.argv[1:]: f


} else if &arg = "b" {

ox()
func main() {

bat();

flag.Parse()

} else {

Alternative implementation: if *b {

eprintln!("invalid
options = {
bar()

argument: {}", arg),

'b': bat
}

'f': fox
if *f {

} else {

}
fox()

eprintln!("missing argu
}

ment");

for option, function in o }


}
ptions:
It is idiomatic to use package flag, and pass
if option in sys. options as -b -f
Alternative implementation:
argv[1:]:
(with a dash).
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");

}

Python
Kotlin
Go
Rust
Dart
Ruby
163 Print list elements by for x in zip(list[::2], l import "fmt" for pair in list.chunks(2) list.each_slice(2){|slice| p sl
group of 2 ist[1::2]):
{
ice}
Print all the list for i := 0; i+1 < len(list); i += 2 {

print(x) println!("({}, {})", pa


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

original list is called list ir[0], pair[1]);

assuming list length is }


}
even. 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 import webbrowser import "github.com/skratchdot/open-golang/o use webbrowser; cmd = case RbConfig::CONFIG['h
default browser pen" ost_os']

Open the URL s in the webbrowser.open(s) webbrowser::open(s).expect


when /mswin|mingw|cygwin/ th
default browser.
b is not available b := open.Start(s) == nil ("failed to open URL");

en "start "

Set boolean b to indicate when /darwin/ then "open "

whether the operation Alternative implementation:


when /linux|bsd/ then "xdg-o
was successful. func openbrowser(url string) {
pen "

var err error


else raise "No OS detected"

end

switch runtime.GOOS {

case "linux":
b = system cmd + s
err = exec.Command("xdg-ope
b contains the info which is returned
n", url).Start()

by the OS
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)

}

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

last element of list Alternative implementation:


There is no shortcut, use len!

items. Alternative implementation:


Panics if the list is empty. x = items[-1]
let x = items.last().unwrap
();
last() returns an Option<&T>
166 Concatenate two lists ab = a + b val ab = a + b ab := append(a, b...) let ab = [a, b].concat(); var a = [1,2,3];
ab = a + b
Create list ab containing var b = [3,2,4];

Warning! a and ab may or may not share the same Returns a new array.
all the elements of list a, var ab = a + b;
underlying memory.
followed by all elements
Lines 1 and 2 are just
of list b. Alternative implementation: initializing the a and b
var ab []T
variables.

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

This ensures that ab is a new list (not sharing any On line 3 we initialize
memory with a and b).
ab with the result of
T is the type of the elements. concatenating a and b
together with the +
Alternative implementation: operator.
ab := make([]T, len(a)+len(b))

copy(ab, a)

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

167 Trim prefix t = s[s.startswith(p) and import "strings" let t = s.trim_start_matche t = s.sub(/\A#{p}/, "")
Create string t consisting len(p):] s(p);
t := strings.TrimPrefix(s, p) Like Strings, Regular Expressions
of string s with its prefix
Warning: this would remove support interpolation. \A means :
p removed (if s starts Alternative implementation: several leading occurrences of beginning of string
with p).
t = s.removeprefix(p) p, if present.

See strip_prefix to remove only Alternative implementation:


removeprefix is in Python
3.9+ one occurrence. t = s.delete_prefix(p)
available since Ruby 2.5.0
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.
168 Trim suffix t = s.removesuffix(w) import "strings" let t = s.trim_end_matches t = s.sub(/#{w}\z/, "")
Create string t consisting (w);
removesuffix is in Python 3.9+ t := strings.TrimSuffix(s, w) Like Strings, Regular expressions can
of string s with its suffix
This may remove several be interpolated. \z means "end of
w removed (if s ends
occurrences of w at the end of s. string".
with w).
Alternative implementation: Alternative implementation:
let t = s.strip_suffix(w).u t = s.delete_suffix(w)
nwrap_or(s); Introduced in Ruby 2.5.0
Removes at most 1 occurrence
of w

Python
Kotlin
Go
Rust
Dart
Ruby
169 String length n = len(s) val n = s.length import "unicode/utf8" let n = s.chars().count(); int n = s.length; n = s.length
Assign to integer n the
If s is a Python 3 str, len(s) n := utf8.RuneCountInString(s) This is kind of roundabout
number of characters of Alternative implementation:
returns the number of because the default len method
string s.
This assumes that s is encoded in UTF-8 (which is
characters. If s is a Python 3 gives bytes, not characters. n = s.size
Make sure that multibyte idiomatic in Go).
bytes, len(s) returns the
characters are properly
number of bytes.
handled.

n can be different from


the number of bytes of s.
170 Get map size n = len(mymap) n := len(mymap) let n = mymap.len(); 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 s.append(x) s = append(s, x) s.push(x); s.add(x); s << x
end of a list
Append element x to the
list s.
172 Insert an entry in a m[k] = v m[k] = v use std::collection::HashMa m[k] = v; m[k] = v
map p;
If m[k] already exists, then it is If m[k] already exists, then it is overwritten.
Insert value v for key k
overwritten. m.insert(k, v);
in map m.
173 Format a number with f'{1000:,}' import "golang.org/x/text/language"
use separator::Separatable; '1000'.gsub(/\B(?=(...)*\b)/,
grouped thousands import "golang.org/x/text/message" ',')
Number will be formatted Alternative implementation: println!("{}", 1000.separat
with a comma separator p := message.NewPrinter(language.English)
ed_string());
format(1000, ',') Alternative implementation:
between every group of s := p.Sprintf("%d\n", 1000) Requires the separator crate
require 'active_support/all'
thousands.
Alternative implementation: Alternative implementation: 1000.to_s(:delimited)
'{:,}'.format(1000) import "github.com/floscodes/golang-thousan
requires packages ruby-
ds"

activesupport, ruby-bigdecimal and


import "strconv"
ruby-json
n := strconv.Itoa(23489)

Alternative implementation:
s := thousands.Separate(n, "en")
'1000'.reverse.scan(/.{1,3}/).j
This uses a third-pary package golang-thousands
oin(',').reverse

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

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


data=data, method="POST")

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

q) import "net/http"
use std::io::Read;
Explicit use of the "method" import "net/url"
parameter, because "GET" is let client = reqwest::block
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 s = a.hex() import "encoding/hex" use hex::ToHex; s = a.unpack("H*")
From array a of n bytes,
build the equivalent hex s := hex.EncodeToString(a) let mut s = String::with_ca
string s of 2n digits.
pacity(2 * a.len());

Each byte (256 possible a.write_hex(&mut s).expect


values) is encoded as ("Failed to write");
two hexadecimal
characters (16 possible Alternative implementation:
values per digit). use core::fmt::Write;

let mut s = String::with_ca


pacity(2 * n);

for byte in a {

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


e)?;

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

Python
Kotlin
Go
Rust
Dart
Ruby
177 Find files with a given import os import "path/filepath"
L = Dir.glob(File.join("**",
list of filename import "strings" "*.{jpg,jpeg,png}"), base: D)
extensions extensions = [".jpg", ".j
Construct a list L that peg", ".png"]
L := []string{}

contains all filenames L = [f for f in os.listdi err := filepath.Walk(D, func(path string, i


that have the extension r(D) if os.path.splitext nfo os.FileInfo, err error) error {

".jpg" , ".jpeg" or ".png" (f)[1] in extensions]


if err != nil {

in directory D and all it's Doesn't look in subdirectories fmt.Printf("failure accessi


subdirectories. because I didn't read the ng a path %q: %v\n", path, err)

question properly. return err

Alternative implementation: for _, ext := range []string{".jp


import re
g", ".jpeg", ".png"} {

import os if strings.HasSuffix(path,
ext) {

filtered_files = ["{}/ L = append(L, path)

{}".format(dirpath, filen break

ame) for dirpath, _, file }

names in os.walk(D) for f }

ilename in filenames if r return nil

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]

Python
Kotlin
Go
Rust
Dart
Ruby
178 Check if point is inside b = (x1 < x < x2) and (y1 import "image" struct Rect {
Point = Struct.new(:x, :y)

rectangle < y < y2) x1: i32,

Set boolean b to true if if p := image.Pt(x, y)

Edges NOT considered to be x2: i32,


Rect = Struct.new(:x1, :y1, :x
the point with r := image.Rect(x1, y1, x2, y2)

inside. y1: i32,


2, :y2) do

coordinates (x,y) is b := p.In(r)


y2: i32,
def contains?(point)

inside the rectangle with Points on the edge of the rectangle are considered }
point.x.between?(x1,x2) &&
coordinates as in the rectangle. point.y.between?(y1,y2)

(x1,y1,x2,y2) , or to impl Rect {


end

false otherwise.
fn contains(&self, x: i end

Describe if the edges are 32, y: i32) -> bool {

considered to be inside return self.x1 < x b = Rect.new(0,0,2,5).contains?


the rectangle. && x < self.x2 && self.y1 < (Point.new(0,0))
y && y < self.y2;
Ruby has no predefined Rect or Point
}
classes. Edges are considered to be
} inside.
179 Get center of a center = ((x1+x2)/2, (y1+ fun center(x1: in import "image" struct Rectangle {
Point = Struct.new(:x, :y)

rectangle y2)/2) t, y1: int, x2: i x1: f64,

Return the center c of c := image.Pt((x1+x2)/2, (y1+y2)/2)


center is a tuple that can be nt, y2: int) = Pa y1: f64,
Rect = Struct.new(:x1, :y1, :x
the rectangle with ir((x1 + x2)/2, Implementation for x1, x2, y1 and y2 as int. x2: f64,
2, :y2) do

accessed using index 0 for x


coördinates(x1,y1,x2,y2) (y1 + y2)/2)
y2: f64,
def center

and 1 for y.
}
Point.new((x1+x2)/2.0, (y1+

e.g. center[0] y2)/2.0)

impl Rectangle {
end

Alternative implementation: pub fn center(&self) -> end

from collections import n (f64, f64) {

amedtuple ((self.x1 + sel c = Rect.new(0,0,2,5).center


f.x2) / 2.0, (self.y1 + sel Ruby has no predefined Point or Rect
Point = namedtuple('Poin f.y2) / 2.0)
class. This code returns: <struct Point
t', 'x y')
}
x=1.0, y=2.5>
center = Point((x1+x2)/2, }
(y1+y2)/2)

center is a namedtuple, that


can be accessed either using x
and y or an index (0,1)

e.g. center.x or center[0]


180 List files in directory import os import "io/ioutil" use std::fs; x = Dir.children(d)
Create list x containing
. and .. not included
the contents of directory x = os.listdir(d) x, err := ioutil.ReadDir(d) let x = fs::read_dir(d).unw
d.
x is a slice of os.FileInfo rap();

x is a fs::ReadDir iterator over


x may contain files and std::io::Result<fs::DirEntry>
subfolders.

No recursive subfolder Alternative implementation:


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

Python
Kotlin
Go
Rust
Dart
Ruby
182 Quine program s = 's = %r\nprint(s%%s)'
package main
fn main() {
eval s="print 'eval s=';p s"
Output the source of the print(s%s) let x = "fn main() {\n
program. import "fmt"
let x = ";

let y = "print!(\"{}
func main() {
{:?};\n let y = {:?};\n
fmt.Printf("%s%c%s%c\n", s, 0x60, {}\", x, x, y, y)\n}\n";

s, 0x60)
print!("{}{:?};

}
let y = {:?};

{}", x, x, y, y)

var s = `package main


}

import "fmt"
Alternative implementation:
fn main(){print!("{},
func main() {
{0:?})}}","fn main(){print!
fmt.Printf("%s%c%s%c\n", s, 0x60, (\"{},{0:?})}}\"")}
s, 0x60)

var s = `

183 Make HTTP PUT import requests import "net/http" require 'net/http'
request
Make a HTTP request content_type = 'text/plai req, err := http.NewRequest("PUT", u, body)
http = Net::HTTP.new(u)

with method PUT to URL n'


if err != nil {
response = http.send_request('P
u headers = {'Content-Typ return err
UT', path, body)
e': content_type}
}
If port is not given, the default port for
data = {}
req.Header.Set("Content-Type", contentType)
http(s) is used.

req.ContentLength = contentLength
Body and headers are optional.
r = requests.put(u, heade response, err := http.DefaultClient.Do(req)
rs=headers, data=data)
This assumes you know contentLength
status_code, content = r. beforehand.

status_code, r.content
body is a io.Reader which can be nil.
184 Tomorrow from datetime import dat import "time" let t = chrono::Utc::now(). var now = new Date require "date"
Assign to variable t a e, timedelta date().succ().to_string(); Time.now();

string representing the t := time.Now().Add(24 * time.Hour).Format t = (Date.today + 1).to_s


var t = now.add(ne
day, month and year of t = str(date.today() + ti ("2006-01-02")
w Duration(days:
the day after the current medelta(days=1)) Alternative implementation:
1));
date. require 'active_suport'

t = 1.day.since.to_s

Alternative implementation:
require "date"

t = Date.tomorrow.to_s

tomorrow is a Ruby on Rails method



Python
Kotlin
Go
Rust
Dart
Ruby
185 Execute function in 30 import threading import "time" use std::time::Duration;
Thread.new do

seconds use std::thread::sleep; sleep 30

Schedule the execution timer = threading.Timer(3 timer := time.AfterFunc(

f(42)

of f(42) in 30 seconds. 0.0, f, args=(42,) )


30*time.Second,
sleep(Duration::new(30,
end

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

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 sys import kotlin.sys import "os" use std::process::exit; exit
Exit a program cleanly tem.exitProcess
A good article on exit is available at
indicating no error to OS sys.exit(0) os.Exit(0) exit(0);
exitProcess(0) https://www.honeybadger.io/blog/how-
Since exit() ultimately “only”
Alternative implementation: to-exit-a-ruby-program/
raises an exception, it will only
exit the process when called import "os"
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

Python
Kotlin
Go
Rust
Dart
Ruby
187 Disjoint Set class UnionFind:
require 'set'
Disjoint Sets hold def __init__(self, si
elements that are a.disjoint?(b)
ze):

partitioned into a number self.rank = [0] * a and b both being Sets


of disjoint (non- size

overlapping) sets. 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 numpy as np import "gonum.org/v1/gonum/mat" require 'matrix'


Perform matrix
multiplication of a real c = a @ b
c := new(mat.Dense)
c = a * b
matrix a with nx rows Python 3.5 (PEP465) c.Mul(a, b) If a and b are Matrix objects (require
and ny columns, a real introduced the @ operator for 'matrix', which is in standard library, is
matrix b with ny rows matrix multiplication. not needed if you don't construct
and nz columns and these objects)
assign the value to a real Alternative implementation:
matrix c with nx rows import numpy as np
and nz columns.
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.

Python
Kotlin
Go
Rust
Dart
Ruby
189 Filter and transform y = [T(e) for e in x if P var y []Result
let y = x.iter()
y = x.each_with_object([]){|e,
list (e)] for _, e := range x {
.filter(P)
ar| ar << t(e) if p(e)}
Produce a new list y if P(e) {
.map(T)

containing the result of Alternative implementation: y = append(y, T(e))


.collect::<Vec<_>> Alternative implementation:
function T applied to all }
();
y = list(map(T, filter(P, y = x.filter_map{|e| t(e) if p
elements e of list x that }
x))) (e)}
match the predicate P.
No functional style: just a regular loop.
filter_map is available for
enumerables since Ruby 2.7.
y is not fully allocated upfront because the number
of matching elements is not known yet.
190 Call an external C // void foo(double *a, int n);
extern "C" {

function // double a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, /// # Safety

Declare an external C 9};


///

function with the import "C"


/// `a` must point to a
prototype
n array of at least size 10

C.foo(C.a, 10) fn foo(a: *mut libc::c_


void foo(double *a, int n);
double, n: libc::c_int);

and call it, passing an


array (or a list) of size 10 let mut a = [0.0, 1.0, 2.0,
to a and 10 to n.
3.0, 4.0, 5.0, 6.0, 7.0, 8.
0, 9.0];

Use only standard let n = 10;

features of your unsafe {

language. foo(a.as_mut_ptr(), n);

191 Check if any value in a if any(v > x for v in a):


for _, v := range a {
if a.iter().any(|&elem| ele f if a.any?{|v| v > x }
list is larger than a f() if v > x {
m > x) {

limit f()
f()

Given a one-dimensional break


}
array a, check if any }

value is larger than x, }


and execute the
procedure f if that is the
case
192 Declare a real variable import decimal import "math/big" use rust_decimal::Decimal;
require 'bigdecimal'
with at least 20 digits use std::str::FromStr;
Declare a real variable a a = decimal.Decimal('1234 a, _, err := big.ParseFloat("123456789.1234 a = BigDecimal('1234567890.1234
with at least 20 digits; if 567890.123456789012345') 56789123465789", 10, 200, big.ToZero) let a = Decimal::from_str 5678901')
the type does not exist, 2nd arg is the base.
("1234567890.12345678901234
issue an error at compile 3rd arg is the precision.
5").unwrap();
time. 4th arg is the rounding mode.

The precision is the maximum number of mantissa


bits available to represent the value.

Python
Kotlin
Go
Rust
Dart
Ruby
193 Transpose a two- import numpy as np a = [[1,2], [3,4], [5,6]]

dimensional matrix b = a.transpose


Declare two two- a = np.array([[1,2], [3,
dimensional arrays a 4], [5,6]])

and b of dimension n*m b = a.T

and m*n, respectively.


Assign to b the Alternative implementation:
transpose of a (i.e. the a = [[1,2], [3,4], [5,6]]

value with index b = list(map(list, zip(*


interchange). a)))

194 Circular shift of a two- import numpy as np b = a.map{|ar| ar.rotate(n) }


dimensional array
b = np.roll(a, m, axis=1) Negative n is fine
Given an array a, set b
to an array which has
the values of a along its
second dimension
shifted by n. Elements
shifted out should come
back at the other end.
195 Pass a two- def foo(a):
#[macro_use] extern crate i def foo(ar)

dimensional array print(len(a))


tertools; puts "Array size: #{ar.size},
Pass an array a of real print(sum(
#{ar.max.size}."

numbers to the fn foo(a: Vec<Vec<usize>>)


x*(i+1) + y*(i+1) ar.each.with_index(1).sum do
procedure (resp. {

*2 for i, (x, y) in enume |a, i|

function) foo. Output the rate(a)


println!(

a.each.with_index(1).sum do
size of the array, and the "Length of array:
)) |el, j|

sum of all its elements {}",

el*i*j

when each element is a.clone()

end

multiplied with the array .into_iter()

end

indices i and j (assuming .flatten()

end

they start from one). .collect::<Vec<


usize>>()

puts foo(array)
.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

Python
Kotlin
Go
Rust
Dart
Ruby
196 Pass a sub-array def foo(data, r):
fn foo(el: &mut i32) {
# @param a [Array<Integer>]

Given an integer array a for i in r: data[i] = *el = 42;


#

of size n, pass the first, 42


}
# @return [Array<Integer>]

third, fifth and seventh, return


a.iter_mut().take(m).step_b #

... up to the m th element y(2).for_each(foo); def foo(a)

to a routine foo which foo(a, range(0, m+1, 2)) a.fill(42)

sets all these elements end

to 42.
foo(arry.select(&:odd?))

# For older versions of ruby:

# foo(arry.select { |x| x.odd?


})

197 Get a list of lines from with open(path) as f:


import "io/ioutil"
use std::io::prelude::*;
lines = open(path).readlines
a file lines = f.readlines() import "strings" use std::io::BufReader;

Retrieve the contents of use std::fs::File;


file at path into a list of func readLines(path string) ([]string, erro
strings lines, in which r) {
let lines = BufReader::new
each element is a line of b, err := ioutil.ReadFile(path)
(File::open(path).unwrap())

the file. if err != nil {


.lines()

return nil, err


.collect::<Vec<_>>
}
();
lines := strings.Split(string(b),
"\n")

return lines, nil

198 Abort program import sys import "os" use std::process; exit x
execution with error
condition sys.exit(x) os.Exit(x) process::exit(x);
Abort program execution This does not run any
with error condition x destructors. Clean up is left to
(where x is an integer the OS.
value)
199 Truncate a file at the F.truncate(F.tell()) import "os" F.truncate(F.pos)
current file position
Truncate a file F at the err := os.Truncate(F, position)
given file position.
200 Return hypotenuse import math import "math" fn hypot(x:f64, y:f64)-> f6 include Math
Returns the hypotenuse 4 {

h of the triangle where h = math.hypot(x, y) h := math.Hypot(x, y) h = hypot(x, y)


let num = x.powi(2) +
the sides adjacent to the y.powi(2);

square angle have num.powf(0.5)

lengths x and y. }

201 Euclidean norm import numpy as np require 'matrix'


Calculate n, the
Euclidean norm of data np.linalg.norm(data) data = Vector[5.0, 4.0, 3.0, 2.
(an array or list of 0, 1.0]

floating point values). n = data.norm



Python
Kotlin
Go
Rust
Dart
Ruby
202 Sum of squares s = sum(i**2 for i in dat import "math" let s = data.iter().map(|x| s = data.sum{|i| i**2}
Calculate the sum of a) x.powi(2)).sum::<f32>();
var s float64
Can be written as data.sum{ _1**2 }
squares s of data, an
for _, d := range data {
since Ruby 2.7

array of floating point


values. s += math.Pow(d, 2)

203 Calculate mean and import statistics import "github.com/gonum/stat" m = data.sum / data.length.to_
standard deviation f

Calculate the mean m m = statistics.mean(data)


m, s := stat.MeanStdDev(data, nil)
sd = Math.sqrt data.sum { |n|
and the standard sd = statistics.stdev(dat github.com/gonum/stat is a third party package, but (m-n)**2 } / data.length.to_f

deviation s of the list of a)


well established.
.to_f forces floating point
floating point values
data.
204 Return fraction and import math import "math" puts Math::frexp(a)
exponent of a real
number print(math.frexp(a)) fmt.Println(math.Frexp(a))
Given a real number a,
print the fractional part
and the exponent of the
internal representation of
that number. For 3.14,
this should print
(approximately)

0.785 2


Python
Kotlin
Go
Rust
Dart
Ruby
205 Get an environment import os import "os" use std::env; foo = ENV["FOO"]
variable
try:
foo, ok := os.LookupEnv("FOO")
let foo;
Returns nil if "FOO" is absent.
Read an environment
variable with the name foo = os.environ['FO if !ok {
match env::var("FOO") {

"FOO" and assign it to O']


foo = "none"
Ok(val) => foo = val,

the string variable foo. If except KeyError:


} Err(_e) => foo = "non
it does not exist or if the foo = "none" e".to_string(),

system does not support Alternative implementation: }


environment variables, Alternative implementation: import "os"
assign a value of "none". from os import getenv Alternative implementation:
foo := os.Getenv("FOO")

use std::env;
foo = getenv('FOO', 'non if foo == "" {

e') foo = "none"


let foo = env::var("FOO").u
} nwrap_or("none".to_string
Alternative implementation: This is fine if empty string means "no value" in your ());
import os use case.

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.
Python exposes environment let foo = match env::var("F
variables as an associative OO") {

array(dict), so the standard get Ok(val) => val,

method can be used. Err(_e) => "none".to_st


ring(),

};

Alternative implementation:
use std::env;

if let Ok(tnt_root) = env::


var("TNT_ROOT") {

//

}

Python
Kotlin
Go
Rust
Dart
Ruby
206 Switch statement with switch = {'foo': foo,
switch str {
match str {
method(str).call if ["foo", "ba
strings 'bar': bar,
case "foo":
"foo" => foo(),
r", "baz", "barfl"].include?(st
Execute different 'baz': baz,
foo()
"bar" => bar(),
r)
procedures foo, bar, 'barfl': barfl
case "bar":
"baz" => baz(),

baz and barfl if the }


bar()
"barfl" => barfl(),

string str contains the case "baz":


_ => {}

name of the respective switch_funct = switch.get baz()


}

procedure. Do it in a way (string)


case "barfl":

natural to the language. if switch_funct : switch_ barfl()

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 def func():
a := make([]T, n) let a = vec![0; n]; a = Array.new(n)
automatically a = [0] * n
Elements have type T.
Heap allocations are deallocated
deallocated # local variable auto a is garbage-collected after the program exits its when the variable goes out of
Allocate a list a matically deallocated at scope, unless we let it "escape" by taking its scope.
containing n elements (n end of function

reference.

assumed to be too large return The runtime decides if a lives in the stack on in the
for a stack) that is
heap.
automatically
deallocated when the
program exits the scope
it is declared in.
208 Formula with arrays import math import "math" for i in 0..a.len() {
a = a.zip(b,c,d).map{|i,j,k,l|
Given the arrays a,b,c,d a[i] = e * (a[i] + e*(i+j*k+Math::cos(l)) }
of equal length and the for i in xrange(len(a)):
func applyFormula(a, b, c, d []float64, e f
b[i] * c[i] + d[i].cos());

scalar e, calculate a = e* a[i] = e*(a[i] + loat64) {

}
(a+b*c+cos(d)).
b[i] + c[i] + math.cos(a for i, v := range a {

[i]))
a[i] = e * (v + b[i] + c[i] Should be sure that all the type
Store the results in a.
+ math.Cos(d[i]))
of the variables should be f32 or
Alternative implementation: }
f64 in order to use the cos()
} method.
import math

a = [e*(a[i] + b[i] + c
[i] + math.cos(d[i])) for
i in range(len(a))]

Python
Kotlin
Go
Rust
Dart
Ruby
209 Type with automatic class T:
type t struct {
struct T {
T = Struct.new(:s, :n)

deep deallocation def __init__(self, s, s string


s: String,
v = T.new("Hello, world", [1,
Declare a type t which n):
n []int
n: Vec<usize>,
4, 9, 16, 25])

contains a string s and self.s = s


}
}
v = nil
an integer array n with self.n = n

variable size, and return


v := t{
fn main() {

allocate a variable v of s: "Hello, world!",


let v = T {

type t. Allocate v.s and v = T('hello world', [1, n: []int{1, 4, 9, 16, 25}, s: "Hello,
v.n and set them to the 4, 9, 16, 25])
} world!".into(),

values "Hello, world!" for del v


n: vec![1,
After v goes out of scope, v and all its fields will be
s and [1,4,9,16,25], 4,9,16,25]

garbage-collected, recursively
respectively. Deallocate };

v, automatically }
deallocating v.s and v.n
When a variable goes out of
(no memory leaks).
scope, all member variables are
deallocated recursively.
210 Compiler version and import sys import "runtime" puts version = RUBY_VERSION
options
Assign, at runtime, the version = sys.version
version := runtime.Version()
compiler version and the options = sys.flags
options the program was
compilerd with to
variables version and
options, respectively,
and 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 import "os" use std::fs; FileUtils.mkpath( path )

Create the folder at path


on the filesystem os.mkdir(path) err := os.Mkdir(path, os.ModeDir) fs::create_dir(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 import "os" use std::path::Path; b = Dir.exist?( path )
Set boolean b to true if
path exists on the b = os.path.isdir(path) info, err := os.Stat(path)
let b: bool = Path::new(pat
filesystem and is a b := !os.IsNotExist(err) && info.IsDir() h).is_dir();
directory; false
otherwise.

Python
Kotlin
Go
Rust
Dart
Ruby
213 Case-insensitive string import itertools use itertools::Itertools; strings = ['ᾲ στο διάολο', 'ὰι
compare στο διάολο', 'ᾺͅΣΤΟ ΔΙΆΟΛΟ', 'Ὰ
Compare four strings in strings = ['ᾲ στο διάολ for x in strings

Ι ΣΤΟ ΔΙΆΟΛΟ']

pair-wise variations. The ο',


.iter()

string comparison can 'ὰι στο διάολ .combinations(2)

strings.combination(2){|a,b| pu
be implemented with an ο',
.filter(|x| x[0].to_low
ts "#{a} equals #{b}: #{a.casec
equality test or a 'ᾺͅΣΤΟ ΔΙΆΟΛ ercase() == x[1].to_lowerca
mp?(b)}" }
containment test, must Ο',
se())

be case-insensitive and 'ᾺΙ ΣΤΟ ΔΙΆΟΛ {

must apply Unicode Ο']


println!("{:?} ==
casefolding. {:?}", 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 s = s.ljust(m, c) import "strings"


s = s.ljust(m, c)
Append extra character import "utf8"
c at the end of string s to
make sure its length is at if n := utf8.RuneCountInString(s); n < m {

least m.
s += strings.Repeat(c, m-n)

The length is the number }


of characters, not the c here is a one-character string
number of bytes.

Python
Kotlin
Go
Rust
Dart
Ruby
215 Pad string on the left s = s.rjust(m, c) import "strings"
use unicode_width::{Unicode s.rjust(m, c)
Prepend extra character import "utf8" WidthChar, UnicodeWidthSt
c at the beginning of r};
string s to make sure its if n := utf8.RuneCountInString(s); n < m {

length is at least m.
s = strings.Repeat(c, m-n) + s
if let Some(columns_short)
The length is the number } = m.checked_sub(s.width())
of characters, not the c here is a one-character string {

number of bytes. 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 s = s.center(m, c) s.center(m,c)

sides
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".

Python
Kotlin
Go
Rust
Dart
Ruby
217 Create a Zip archive import zipfile import "archive/zip"
use zip::write::FileOption
Create a zip-file with import "bytes"
s;
filename name and add with zipfile.ZipFile(nam
import "os"

the files listed in list to e, 'w', zipfile.ZIP_DEFLA let path = std::path::Pat


import "io"

that zip-file. TED) as zip:


h::new(_name);

import "io/ioutil"
for file in list_:
let file = std::fs::File::c
zip.write(file) buf := new(bytes.Buffer)
reate(&path).unwrap();

Files listed in list_ w := zip.NewWriter(buf)


let mut zip = zip::ZipWrite
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.

Python
Kotlin
Go
Rust
Dart
Ruby
218 List intersection c = list(set(a) & set(b)) seta := make(map[T]bool, len(a))
use std::collections::HashS c = a & b
Create the list c for _, x := range a {
et;
Ruby 2.7 introduced an alias: c =
containing all unique Alternative implementation: seta[x] = true

let unique_a = a.iter().col a.intersection(b)


elements that are }

c = list(set(a).intersect lect::<HashSet<_>>();

contained in both lists a setb := make(map[T]bool, len(a))

ion(b)) let unique_b = b.iter().col


and b.
for _, y := range b {

c should not contain any This avoids converting b into a lect::<HashSet<_>>();

setb[y] = true

duplicates, even if a and set prior to the intersection.


}

b do.
let c = unique_a.intersecti
The order of c doesn't on(&unique_b).collect::<Vec
var c []T

matter. <_>>();
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 import re import "regexp" use regex::Regex; t = s.squeeze(" ")
spaces with single
t = re.sub(' +', ' ', s) whitespaces := regexp.MustCompile(`\s+`)
let re = Regex::new(r"\s Just spaces.
space
Create string t from the Only replaces spaces. t := whitespaces.ReplaceAllString(s, " ") +").unwrap();

value of string s with The whitespaces regexp can be reused. let t = re.replace_all(s, "
each sequence of ");
spaces replaced by a Replaces all whitespaces.
single space.

Explain if only the space


characters will be
replaced, or the other
whitespaces as well:
tabs, newlines.
220 Create a tuple value t = (2.5, "hello", -1) t := []interface{}{
let t = (2.5, "hello", -1); t = [2.5, "hello", -1]
Create t consisting of 3 2.5,

Tuples are immutable.


Tuples are like “fixed-length
values having different "hello",

They may be created with collections of values of different


types.
make(chan int),

elements of any type. types”.


} They are strongly typed.
Explain if the elements
A slice of empty interface may hold any values (not
of t are strongly typed or
strongly typed).
not.
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.

Python
Kotlin
Go
Rust
Dart
Ruby
221 Remove all non-digits import re import "regexp" let t: String = s.chars().f t = s.delete("^0-9")
characters ilter(|c| c.is_digit(10)).c
t = re.sub(r"\D", "", s) re := regexp.MustCompile("[^\\d]") ^ Meaning: everything but.
Create string t from ollect();
string s, keeping only t := re.ReplaceAllLiteralString(s, "")
digit characters 0, 1, 2,
3, 4, 5, 6, 7, 8, 9.
222 Find the first index of i = items.index(x) if x i i := -1
let opt_i = items.iter().po i=items.indexOf(x) i = items.index(x) || -1
an element in list n items else -1 for j, e := range items {
sition(|y| *y == x);
.index() is not in Enumerable so use a
Set i to the first index in if e == x {
supported data structure like Array
list items at which the i = j

element x can be found, break


let i = match opt_i {

or -1 if items does not }


Some(index) => index as
contain x. } 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

Python
Kotlin
Go
Rust
Dart
Ruby
223 for else loop items = ['foo', 'bar', 'b items.find { it - items := []string{"foo", "bar", "baz", "qu let mut found = false;
items = ['foo', 'bar', 'baz',
Loop through list items az', 'qux']
> it == "baz" }?. x"}
for item in items {
'qux']

checking a condition. Do let {


if item == &"baz" {
puts items.any?("baz") ? "found
something else if no for item in items:
println("found for _, item := range items {
println!("found i it" : "never found it"
matches are found.
if item == 'baz':
it")
if item == "baz" {
t");

print('found it')
} ?: println("nev fmt.Println("found it")
found = true;

A typical use case is break


er found it") goto forelse
break;

looping through a series else:


}
}

of containers looking for print('never found i }


}

one that matches a t') {


if !found {

condition. If found, an fmt.Println("never found it")


println!("never found i
item is inserted; Alternative implementation: }
t");

otherwise, a new forelse: }


items = ['foo', 'bar', 'b
container is created.

az', 'qux']
Go does not have a for...else construct, but a Rust does not have a for...else
structured goto label works well. construct, so we use a found
These are mostly used
True if "baz" in items el variable.
as an inner nested loop,
se False
and in a location where Alternative implementation:
refactoring inner logic This uses python's ternary
operator: <statement1> if if let None = items.iter().
into a separate function
<condition> else <statement2>.
find(|&&item| item == "rock
reduces clarity.
The "in" operator is more star programmer") {

idiomatic than looping over a println!("NotFoun


container. However the run- d");

time performance is tied to the };

type of collection being iterated


over. Alternative implementation:
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.

Python
Kotlin
Go
Rust
Dart
Ruby
224 Add element to the items = [x] + items items = append([]T{x}, items...) use std::collections::VecDe items.unshift(x)
beginning of the list que;
items has type []T.

Insert element x at the Alternative implementation: Alternative implementation:


This implementation always allocates a full new items.push_front(x);
beginning of list items.
items.insert(0, x) slice. items.prepend(x)

prepend is an alias for unshift


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 def f(x=None):
func f(x ...int) {
fn f(x: Option<()>) {
def f( x=nil )

optional argument if x is None:


if len(x) > 0 {
match x {
puts x ? "present" : "not pre
Declare an optional print("Not presen println("Present", x[0])
Some(x) => println! sent"

integer argument x to t")


} else {
("Present {}", x),
end

procedure f, printing out else:


println("Not present")
None => println!("N
"Present" and its value if print("Present", }
ot present"),

it is present, "Not x) } }

present" otherwise }
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 items.pop() items = items[:len(items)-1] items.pop(); items.pop
from list
If items is already empty, this will panic with "slice items is a mutable Vec items.pop(2) would remove (and
Remove the last element
bounds out of range". return) the last 2.
from list items.
227 Copy list y = x[:] y := make([]T, len(x))
let y = x.clone(); y = x.dup
Create new list y copy(y, x) The elements type must
containing the same
Elements have type T
implement the trait
elements as list x.

Note that the destination is the first argument of std::clone::Clone


copy.
Subsequent
modifications of y must
not affect x (except for
the contents referenced
by the elements
themselves if they
contain pointers).
228 Copy a file import shutil import "io/ioutil"
use std::fs; require 'fileutils'
Copy the file at path src import "os"
to dst. shutil.copy(src, dst) fs::copy(src, dst).unwrap FileUtils.copy(src, dst)
();

Python
Kotlin
Go
Rust
Dart
Ruby
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"

Python
Kotlin
Go
Rust
Dart
Ruby
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" require 'timeout'
Cancel an ongoing
processing p if it has not ctx, cancel := context.WithTimeout(context. Timeout::timeout(5) { p }
finished after 5s. Background(), 5*time.Second)
p happens to be an existing method,
defer cancel()
so not a very advisable name for a
p(ctx) method. It will work though.

p is responsible for shutting down gracefully when When it does time out, this results in a
ctx is canceled. TimeOut::Error object, which should
be rescued.
231 Test if bytes are a valid try:
import "unicode/utf8" let b = std::str::from_utf8 b = s.force_encoding("UTF-8").v
UTF-8 string s.decode('utf8')
(&bytes).is_ok(); alid_encoding?
Set b to true if the byte b := utf8.Valid(s)
b = True
example: s = "\xc2"
sequence s consists except UnicodeError:
s is a []byte.
entirely of valid UTF-8 b = False

character code points,


false otherwise.

Python
Kotlin
Go
Rust
Dart
Ruby
232 Read a command line import argparse import "flag" use clap::{Arg, App};
boolean flag
Print "verbose is true" if parser = argparse.Argumen var verbose = flag.Bool("v", false, "verbos let matches = App::new("My
the flag -v was passed to tParser()
e")
Program")

the program command parser.add_argument('-v', flag.Parse()


.arg(Arg::w
line, "verbose is false" action='store_true', dest fmt.Println("verbose is", *verbose) ith_name("verbose")

otherwise. ='verbose')
verbose has pointer type *bool.
.short
args = parser.parse_args Call Parse only once, after all flags are defined and ("v")

()
before flags are read.
.takes_
print('verbose is', args. Flags must be passed before the non-flag value(false))

verbose)
arguments. .get_matche
s();

if matches.is_present("verb
ose") {

println!("verbose is tr
ue")

} else {

println!("verbose is f
alse")

233 Read a command line import argparse import "flag"


string flag
Print the value of the flag parser = argparse.Argumen var country = flag.String("country", "Canad
-country passed to the tParser()
a", "user home country")

program command line, parser.add_argument('-cou flag.Parse()

or the default value ntry', default='Canada', fmt.Println("country is", *country)


"Canada" if no such flag dest='country')
country has pointer type *string.

was passed. args = parser.parse_args Call Parse only once, after all flags are defined and
()
before flags are read.

print('country is', args. Flags must be passed before the non-flag


country)
arguments.
234 Encode bytes to import base64 import "encoding/base64" let s = base64::encode(dat require 'base64'
base64 a);
Assign to string s the b = base64.b64encode(dat s := base64.StdEncoding.EncodeToString(dat s = Base64.strict_encode64(dat
standard base64 a)
a) a)
encoding of the byte s = b.decode()
array data, as specified b is a bytes object

by RFC 4648. s is a unicode string


235 Decode base64 import base64 import "encoding/base64" let bytes = base64::decode require "base64"
Assign to byte array (s).unwrap();

data the bytes data = base64.decode(s) data, err := base64.StdEncoding.DecodeStrin data = Base64.strict_decode64
represented by the g(s) (s)
base64 string s, as
specified by RFC 4648.

Python
Kotlin
Go
Rust
Dart
Ruby
236 Large quotient import fractions import "math/big" q = Rational(a, b)
Initialize a quotient q =
a/b of arbitrary precision. q = fractions.Fraction(a, q := new(big.Rat)

a and b are large b) q.SetString(str)


integers. 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 c := a ^ b let c = a ^ b; c = a ^ b
Assign to c the result of
a, b, c have the same integer type (signed or
(a xor b)
unsigned)

Alternative implementation:
import "math/big"

c := new(big.Int)

c.Xor(a, b)
a, b, c have big integer type *big.Int
238 Xor byte arrays c = bytes([aa ^ bb for a c := make([]byte, len(a))
let c: Vec<_> = a.iter().zi c = a.zip(b).map{|aa, bb| aa ^
Write in a new byte array a, bb in zip(a, b)]) for i := range a {
p(b).map(|(x, y)| x ^ y).co bb}
c the xor result of byte c[i] = a[i] ^ b[i]
llect();
arrays a and b.
}
Byte slices []byte are more idiomatic than arrays.
a and b have the same
size. 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.



Python
Kotlin
Go
Rust
Dart
Ruby
239 Find first regular import re import "regexp" use regex::Regex; x = s.match(/\b\d{3}\b/).to_s
expression match
Assign to string x the m = re.search(r'\b\d\d\d re := regexp.MustCompile(`\b\d\d\d\b`)
let re = Regex::new(r"\b\d
first word of string s \b', s)
x := re.FindString(s) \d\d\b").expect("failed to
consisting of exactly 3 x = m.group(0) if m else re may (and should) be reused.
compile regex");

digits, or the empty '' \b matches word boundaries.


let x = re.find(s).map(|x|
string if no such match \d matches a single digit. x.as_str()).unwrap_or("");
exists.

A word containing more


digits, or 3 digits as a
substring fragment, must
not match.
240 Sort 2 lists together import operator import "sort" let mut tmp: Vec<_> = a.ite a, b = a.zip(b).sort.transpose

Lists a and b have the r().zip(b).collect();

same length. Apply the temp = list(zip(a, b))


type sorter struct {

tmp.as_mut_slice().sort_by_
same permutation to a temp.sort(key=operator.it k []K

key(|(&x, _y)| x);

and b to have them emgetter(0))


t []T

let (aa, bb): (Vec<i32>, Ve


sorted based on the a, b = zip(*work) }

c<i32>) = tmp.into_iter().u
values of a. 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.
241 Yield priority to other import "runtime" ::std::thread::yield_now();

threads busywork();
Explicitly decrease the runtime.Gosched()

priority of the current busywork()


process, so that other After Gosched, the execution of the current
execution threads have goroutine resumes automatically.
a better chance to
execute now. Then
resume normal
execution and call
function busywork.

Python
Kotlin
Go
Rust
Dart
Ruby
242 Iterate over a set for e in x:
for e := range x {
use std::collections::HashS x.each { |e| f(e) }
Call a function f on each f(e) f(e)
et;
element e of a set x. }
for item in &x {

Alternative implementation: x is implemented as a map whose values are f(item);

list(map(lambda e: f(e), ignored. }


x))
x is a HashSet
It will not work until list
transformation
243 Print list print(a) import "fmt" println!("{:?}", a) print(a); puts a
Print the contents of the
fmt.Println(a) a is a Vec.
Newline automatically This prints 1 element of a per line
list or array a on the
Vec<T> doesn't implement the appended.
standard output. a is a slice.
Alternative implementation:
Display trait, however it
This works fine for simple types and structs.

implements the Debug trait. puts a.join(", ")


It won't dereference pointers.
Prints a single line, with a separator
between elements
244 Print map print(m) import "fmt" println!("{:?}", m); puts m
Print the contents of the
map m to the standard fmt.Println(m)
output: keys and values. 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 print(x) import fmt; println!("{:?}", x); puts x
type
fmt.Println(x) Implement fmt::Debug or Result cam be customized by defining
Print the value of object
fmt::Display for T a to_s method on x
x having custom type T, Will be more relevant if T implements fmt.Stringer
for log or debug.
246 Count distinct c = len(set(items)) distinct := make(map[T]bool)
use itertools::Itertools; c = items.uniq.count
elements for _, v := range items {

Set c to the number of let c = items.iter().unique


distinct[v] = true

distinct elements in list ().count();


}

items. c := len(distinct)

This assumes the type T is comparable with ==



Python
Kotlin
Go
Rust
Dart
Ruby
247 Filter list in-place del_count = 0
j := 0
let mut j = 0;
x.select!(&:p)
Remove all the elements for i in range(len(x)):
for i, v := range x {
for i in 0..x.len() {

from list x that don't if not p(x[i - del_co if p(v) {


if p(x[i]) {

satisfy the predicate p, unt]):


x[j] = x[i]
x[j] = x[i];

without allocating a new del x[i - del_cou j++


j += 1;

list. nt]
}
}

Keep all the elements del_count += 1 }


}

that do satisfy p.
x = x[:j] x.truncate(j);
This is O(n^2)
Discarded elements are overwritten.

For languages that don't Alternative implementation:


x is resliced to its new length.

have mutable lists, refer


If the elements of x have a pointer type, then you x.retain(p);
to idiom #57 instead.
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 import math
floating-point value
Construct the "double sign = -1 if s else 1

precision" (64-bit) d = math.ldexp(sign*m,e)


floating point number d
from the mantissa m, the
exponent e and the sign
flag s (true means the
sign is negative).
249 Declare and assign a, b, c = 42, 'hello', 5. a, b, c := 42, "hello", 5.0 let (a, b, c) = (42, "hell a, b, c = 42, 'hello', 5.0
multiple variables 0 o", 5.0);
a, b and c may have different types. Types may differ.
Define variables a, b and
a, b and c may have different a, b, and c may have different
c in a concise way.

types. types.
Explain if they need to
have the same type.

Python
Kotlin
Go
Rust
Dart
Ruby
250 Pick a random value import random import "math/rand" x = m.values.sample
from a map
x = random.choice(list(m. func pick(m map[K]V) V {
m.values.sample(3) would result in 3
Choose a value x from
values())) k := rand.Intn(len(m))
random values
map m.

m must not be empty. i := 0

Ignore the keys. 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 i = int(s, 2) import "strconv" let i = i32::from_str_radix var i = int.parse i = s.to_i(2)
Extract integer value i (s, 2).expect("Not a binary (s, radix: 2);

i, err := strconv.ParseInt(s, 2, 0) The 2 can be any radix up to 36.


from its binary string number!");
representation s (in radix i has type int64
2)

E.g. "1101" -> 13


252 Conditional x = "a" if condition() el if condition() {
x = if condition() { "a" } x = condition ? "a" : "b"

assignment se "b" x = "a"


else { "b" };
Assign to the variable x } else {
Alternative implementation:
the value "a" if calling x = "b"
x = if condition

the function condition } "a"

returns true, or the value


No syntactic sugar else

"b" otherwise.
"b"

end
Does not repeat x.
253 Print stack trace import inspect import "runtime/debug" use backtrace::Backtrace; puts caller
Print the stack frames of
the current execution for frame in inspect.stac debug.PrintStack() let bt = Backtrace::new();

thread of the program. k():


Prints to standard error println!("{:?}", bt);
print(frame)


Python
Kotlin
Go
Rust
Dart
Ruby
254 Replace value in list for i, v in enumerate(x):
for i, s := range x {
for v in &mut x {
x.map!{|el| el == "foo" ? "bar"
Replace all occurrences if v == "foo":
if s == "foo" {
if *v == "foo" {
: el}

of "foo" with "bar" in the x[i] = "bar" x[i] = "bar"


*v = "bar";

string list x }
}

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 print(x) use std::collections::HashS puts x
Print the values of the et;
set x to the standard
output.
println!("{:?}", x);
The order of the
elements is irrelevant
and is not required to
remain the same next
time.
256 Count backwards for i in range(5, -1, - import "fmt" (0..=5).rev().for_each(|i| for (int i = 5; i 5.downto(0){|n| puts n }
Print the numbers 5, 4, 1):
println!("{}", i));
>= 0; i--) {

..., 0 (included), one line for i := 5; i >= 0; i-- {

print(i) Use _(0..=5).rev()_.


print(i);

per number. fmt.Println(i)

(5..=0) will not do anything. }


}

257 Traverse list for i in range(len(items) import "fmt" for (i, item) in items.iter items.each_with_index.reverse_e
backwards -1, -1, -1):
().enumerate().rev() {
ach{|x, i| puts "#{i} #{x}" }

Print each index i and for i := len(items) - 1; i >= 0; i-- {

print(i, items[i]) println!("{} = {}", i,


value x from the list x := items[i]

*item);

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

}
down to the first. }

258 Convert list of strings b = [int(elem) for elem i import "strconv" let b: Vec<i64> = a.iter(). b = a.map(&:to_i)
to list of integers n a] map(|x| x.parse::<i64>().un
Convert the string values b := make([]int, len(a))

wrap()).collect();
from list a into a list of var err error

for i, s := range a {
a has type Vec<&str>
integers b.
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 import re import "regexp" let parts: Vec<_> = s.split parts = s.split( Regexp.union
separators (&[',', '-', '_'][..]).coll (",", "-", "_") )
Build list parts parts = re.split('[,_ re := regexp.MustCompile("[,\\-_]")

ect(); Regexp.union takes care of escaping


consisting of substrings \-]', s) parts := re.Split(s, -1)
the "-".
of input string s, Square brackets mean "match any of these
separated by any of the characters".

characters ',' (comma), '-' The special character dash must be escaped with a
(dash), '_' (underscore). backslash.

The backslash must be escaped with a backslash.



Python
Kotlin
Go
Rust
Dart
Ruby
260 Create an empty list of items = [] var items []string let items: Vec<String> = ve var items = <Strin items = []
strings c![]; g>[];
items is nil, which is idiomatic for an empty slice
Declare a new list items
of string elements, Alternative
containing zero elements implementation:
var items = <Strin
g>[];

261 Format time hours- import datetime import "time" use time::macros::format_de d = Time.now

minutes-seconds scription; x = d.strftime("%H:%M:%S")


Assign to string x the d = datetime.datetime.now x := d.Format("15:04:05")
value of fields (hours, ()
let format = format_descrip
minutes, seconds) of x = d.strftime('%H:%M:% tion!("[hour]:[minute]:[sec
date d, in format S') ond]");

HH:MM:SS. let x = d.format(&format).e


xpect("Failed to format the
time");

262 Count trailing zero bits t = bin(n)[::-1].find import "math/bits" let t = n.trailing_zeros(); t = n.digits(2).index(1)

Assign to t the number ('1')


of trailing 0 bits in the t := bits.TrailingZeros(n)
Works for n > 0. Integers in
binary representation of n has type uint
Python have no fixed bitsize,
the integer n.

so t is undefined for n = 0.

E.g. for n=112, n is


1110000 is base 2 and
the result is t=4
263 Integer logarithm in import math fn log2d(n: f64) -> f64 {
def log2d(n) = n.bit_length -
base 2 n.log2().floor()
1

Write two functions def log2d(n):

log2d and log2u, which return math.floor(mat


def log2u(n) = 2 ** log2d(n) ==
calculate the binary h.log2(n))

fn log2u(n: f64) -> f64 {


n ? log2d(n) : log2d(n) + 1

logarithm of their n.log2().ceil()

argument n rounded def log2u(n):

}
(1..12).each{|n| puts "#{n} #
down and up, return math.ceil(mat
{log2d(n)} #{log2u(n)}" }
respectively. n is h.log2(n))

fn main() {

assumed to be positive. for n in 1..=12 {

Print the result of these for n in range(1, 13):

let f = f64::from
functions for numbers print(n, log2d(n), lo
(n);

from 1 to 12. g2u(n))


println!("{} {}
Functions accept both int and {}", n, log2d(f), log2u
float parameters (f));

}
Alternatively, you could use n as
f64 instead of f64::from(n), but
that doesn't pass the Clippy
pedantic lint cast_lossless.

Python
Kotlin
Go
Rust
Dart
Ruby
264 Automated passing of def foo(a):
fn foo(v: Vec<Vec<i32>>) {
def foo(ar)

array bounds print(len(a), len(a println!("{} {}", v.len puts "#{ar.size} #{ar.first.s
Pass a two-dimensional [0]))
(), v[0].len());
ize}"

integer array a to a return


}
end

procedure foo and print


the size of the array in let v = vec![
a = [[1,2,3], [4,5,6]]

each dimension. Do not a = [[1,2,3], [4,5,6]]


vec![1, 2, 3],
foo(a)
pass the bounds foo(a)
vec![4, 5, 6],

manually. Call the ];

procedure with a two- foo(v);


dimensional array.
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 i = 42


let i = 42i32;
i = 42

integer p = bin(i).count('1') % 2 let p = i.count_ones() % 2; i.digits(2).count(1)[0]


Set the integer variable i
to 42 and calculate its
parity (i.e. 0 if it contains
an even number of bits,
1 if it contains an odd
number of bits).
266 Repeating string s = v * n import (
let s = v.repeat(n); var s = v * n; s = v * n
Assign to the string s the "fmt"

String * num repeats


value of the string v "strings"

copies of the string.


repeated n times, and )
write it out.

s := strings.Repeat(v, n)

E.g. v="abc", n=5 ⇒ fmt.Println(s)


s="abcabcabcabcabc"

Python
Kotlin
Go
Rust
Dart
Ruby
267 Pass string to def foo(x):
import "fmt" use std::any::Any; def foo(x)

argument that can be if isinstance(x, st puts x.class == String ? x :


of any type func foo(x interface{}) {
fn foo(x: &dyn Any) {

r):
"Nothing"

Declare an argument x if s, ok := x.(string); ok {


if let Some(s) = x.down
print(x)
end

to a procedure foo that fmt.Println(s)


cast_ref::<String>() {

else:

can be of any type. If the } else {


println!("{}", s);

print('Nothing.')
foo("Hello, world")

type of the argument is a fmt.Println("Nothing.")


} else {

return
foo(42)
string, print it, otherwise }
println!("Nothing")

print "Nothing."
}
}

foo('Hello, world!')

foo(42)

Test by passing "Hello, func main() {

world!" and 42 to the foo("Hello, world!")


fn main() {

procedure. 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:
Vector = Struct.new(:x, :y, :z)
Define a type vector def __init__(self, x, do

containing three floating y, z):


def * (other)

point numbers x, y, and self.x = x


Vector.new(

z. Write a user-defined self.y = y


y*other.z - z*other.y,

operator x that self.z = z


z*other.x - x*other.z,

calculates the cross return


x*other.y - y*other.x)

product of two vectors a end

and b. def __mul__(self, oth end


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 e = T.horse
val e = t.values let e = t::bike;

Given the enumerated s = e.name


().random() // or let s = format!("{:?}", e);

type t with 3 possible print(s)


t.bike, but tha
values: bike, car, horse.
t's boring
println!("{}", s);
Set enum e to one of the val s = e.name
This requires the enum to derive
allowed values of t.
println(s) the Debug trait.
Set string s to hold the
string representation of e
(so, not the ordinal
value).

Print s.

Python
Kotlin
Go
Rust
Dart
Ruby
270 Test for quiet or import math
signaling NaN
Given a floating point if math.isnan(r1):

number r1 classify it as print('This is a quie


follows:
t NaN.')

If it is a signaling NaN, else:

print "This is a signaling print('This is a numb


NaN."
er.')

If it is a quiet NaN, print Python makes no effort to


"This s a quiet NaN."
distinguish signaling NaNs
If it is not a NaN, print from quiet NaNs, and behavior
"This is a number."
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 if isinstance(x, fo


procedure tst is of type o):

foo, print "Same type." If print("Same typ


it is of a type that e.")

extends foo, print elif issubclass(type


"Extends type." If it is (x), foo):

neither, print "Not print("Extends ty


related." pe.")

else:

print("Not relate
d.")

272 Play FizzBuzz for i in range(1,101):


(1..100).each do |i|

Fizz buzz is a children's if i % 15 == 0:


d3 = i % 3 == 0

counting game, and a print("FizzBuzz")


d5 = i % 5 == 0

trivial programming task elif i % 3 == 0:

used to affirm that a print("Fizz")


if d3 && d5

programmer knows the elif i % 5 == 0:


puts "FizzBuzz"

basics of a language: print("Buzz")


elsif d3

loops, conditions and else:


puts "Fizz"

I/O.
print(i) elsif d5

puts "Buzz"

The typical fizz buzz else

game is to count from 1 puts "#{i}"

to 100, saying each end

number in turn. When end

the number is divisible


by 3, instead say "Fizz".
When the number is
divisible by 5, instead
say "Buzz". When the
number is divisible by
both 3 and 5, say
"FizzBuzz"

Python
Kotlin
Go
Rust
Dart
Ruby
273 Check if folder is import os import "os" use std::fs; b = Dir.empty?(p)
empty
Returns true if the named file is an
Set the boolean b to true b = os.listdir(p) == [] dir, err := os.Open(p)
let b = fs::read_dir(p).unw
if err != nil {
rap().count() == 0; empty directory, false if it is not a
if the directory at filepath
panic(err)
directory or non-empty.
p is empty (i.e. doesn't
contain any other files }

and directories) 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 import re import "strings"
t = s.gsub(/[[:space:]]/, "")
space characters import "unicode"
t = re.sub('\\s', '', s) [[:space:]] is a POSIX bracket
Create string t from
t := strings.Map(func(r rune) rune {
expression.
string s, removing all the
spaces, newlines, if unicode.IsSpace(r) {

Alternative implementation:
tabulations, etc. return -1

}
t = s.gsub(/\s/, "")
return r

}, s)

In this mapping, -1 means "drop this character"


275 Binary digits to byte n = (len(s) - 1) // 8 + 1
import "strconv" a = s.scan(/[01]{8}/).map{|slic
array a = bytearray(n)
e| slice.to_i(2).to_s(16).rjust
From the string s n := len(s) / 8

for i in range(n):
(2, "0")}

consisting of 8n binary a := make([]byte, n)

b = int(s[i * 8:(i +
digit characters ('0' or for i := range a {

1) * 8], 2)

'1'), build the equivalent b, err := strconv.ParseInt(s[i*8:i*


a[i] = b

array a of n bytes.
8+8], 2, 0)

Each chunk of 8 binary if err != nil {

digits (2 possible values log.Fatal(err)

per digit) is decoded into }

one byte (256 possible a[i] = byte(b)

values). }

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 x.add(e) x[e] = struct{}{} require 'set'
set
x has type map[E]struct{} x.add(e)
Insert an element e into
the set x. Alternative implementation:
Alternative implementation:
x[e] = true
x << e
x has type map[E]bool

Python
Kotlin
Go
Rust
Dart
Ruby
277 Remove an element x.remove(e) delete(x, e) x.delete(e)
from a set
A KeyError exception is raised x has type map[E]struct{}
If e is absent, this returns x.

Remove the element e


if e was already absent. x.delete?(e) would return nil if e is not
from the set x.

If x is nil or there is no such element, delete is a present.


no-op.
Explains what happens if
e was already absent Alternative implementation:
from x.
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 import sys import "bufio"
line = gets
standard input import "os"
line = sys.stdin.readline EOF returns nil
Read one line into the
string line.
() s := bufio.NewScanner(os.Stdin)

In case of EOF an empty string if ok := s.Scan(); !ok {

Explain what happens if is returned. log.Fatal(s.Err())

EOF is reached. }

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 import sys import "bufio"
use std::io::prelude::*; lines = readlines
from the standard import "os"
lines = sys.stdin.readlin let lines = std::io::stdin run and enter some words in a
input
es() var lines []string
().lock().lines().map(|x| terminal. End by Ctrl-D (EOF).
Read all the lines (until
EOF) into the list of s := bufio.NewScanner(os.Stdin)
x.unwrap()).collect::<Vec<S
strings lines. 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 m = {k:v for k, v in m.it for k, v := range x {
m.select{|k,v| p(v) }
Remove all the elements ems() if p(v)} if !p(v) {
select! (with an exclamation mark)
from the map m that delete(x, k)

Creates a new map. would modify in-place


don't satisfy the }

predicate p.
Alternative implementation: }
Keep all the elements
for k in list(m):
It is safe to use delete while iterating.

that do satisfy p.

if p(m[k]): m.pop(k)
x is filtered in-place.

Explain if the filtering Modifies m in-place, but


happens in-place, i.e. if creates a temporary list of all
m is reused or if a new the keys.
map is created.

Python
Kotlin
Go
Rust
Dart
Ruby
281 Use a Point as a map m = dict()
m := map[Point]string{}
Point = Struct.new(:x, :y)

key p = Point(x=42, y=5)


p := Point{x: 42, y: 5}
m = {Point.new(42, 5) => "Hell
You have a Point with m[p] = 'Hello' m[p] = "Hello" o"}
integer coordinates x
Dictionary keys must be Types comparable with == can be used as map
and y. Create a map m
hashable objects. User-defined keys.
with key type Point (or
classes are hashable by
equivalent) and value
default.
type string. Insert "Hello"
at position (42, 5).
282 Use a custom type as type Foo struct {
Foo = Struct.new(:x, :y)

map key name string


m = {Foo.new(42, 5) => "Hello"}
Declare a type Foo, and x, y int
To be a possible map key, the object
create a new map with }
has to respond to a hash method. By
Foo as key type.

default it does.
m := make(map[Foo]string)
Mention the conditions
Foo can be used as a key type if all of its fields are
on Foo required to make
comparable with ==
it a possible map key
type.
283 Split with a custom parts = s.split(sep) import "strings" let parts = s.split(sep); parts = s.split(sep)
string separator
parts := strings.Split(s, sep) split returns an iterator.

Build the list parts


consisting of substrings parts has type []string.
s may have type &str or String.
of input string s,
separated by the string Alternative implementation:
sep.
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 a = [0] * n a := make([]int, n) let a = vec![0; n]; a = Array.new(n, 0)
integers
All elements have the default value 0.
Create a new list a (or Alternative implementation:
array, or slice) of size n,
a = [0] * n
where all elements are
integers initialized with
the value 0.
285 Set variable to NaN a = float('nan')
a = Float::NAN
Given two floating point
Python makes no effort to Ruby does not differentiate between
variables a and b, set a
distinguish signaling NaNs quiet or signalling NaN's.
to a to a quiet NaN and
from quiet NaNs, and behavior
b to a signalling NaN.
for signaling NaNs remains
Use standard features of
unspecified. Typical behavior is
the language only,
to treat all NaNs as though
without invoking
they were quiet.
undefined behavior.

Python
Kotlin
Go
Rust
Dart
Ruby
286 Iterate over characters for i, c in enumerate(s):
i := 0
for (i, c) in s.chars().enu s.each_char.with_index{|c, i| p
of a string print(f'Char {i} is for _, c := range s {
merate() {
uts "Char #{i} is #{c}" }
Print a line "Char i is c" {c}')
fmt.Printf("Char %d is %c\n", i, c)
println!("Char {} is
for each character c of i++
{}", i, c);

Python strings are sequences


the string s, where i is } }
of Unicode codepoints (not
the character index of c
bytes). c is a rune.
s may have type &str or String.
in s (not the byte index).

s is assumed encoded in UTF-8.

Make sure that multi-


This first range variable is ignored, as it provides
byte characters are
positions in bytes, instead of runes count.
properly handled, and
count for a single
character.
287 Number of bytes of a n = len(s.encode('utf8')) n := len(s) let n = s.len(); n = s.bytesize
string
Python strings are sequences len counts bytes (not runes). The len method counts the
Assign to n the number
of Unicode codepoints, the number of bytes, not the number
of bytes in the string s.

internal representation is of characters.


implementation dependent. But
This can be different
you can easily determine the
from the number of
length of a specific byte
characters. If n includes
encoding.
more bytes than the
characters per se
(trailing zero, length
field, etc.) then explain it.
One byte is 8 bits.
288 Check if set contains a b = e in x b := x[e] let b = x.contains(&e); b = x.include? e
value
x has type map[E]bool x has type HashSet
Set the boolean b to
true if the set x contains Alternative implementation:
the element e, false
_, b := x[e]
otherwise.
x has type map[E]struct{}
289 Concatenate two s = a + b s := a + b let s = format!("{}{}", a, s = a + b
strings b);
Create the string s by
This allocates a new String with
concatenating the strings
a and b concatenated.
a and b.
Alternative implementation:
let s = a + b;
This adds b to the current
allocation of a, meaning that a
needs to be a mutable String.

Python
Kotlin
Go
Rust
Dart
Ruby
290 Sort sublist import functools sub := items[i:j]
items[i..j].sort_by(c);
Sort the part of the list sort.Slice(sub, func(a, b int) bool {

items[i:j] = sorted(items Sorts a slice of items.


items from index i return c(sub[a], sub[b])

(included) to index j [i:j], key=functools.cmp_


})
(excluded), in place, to_key(c))
A slice can be sorted in place.
using the comparator c.
c is an old-style comparison
function
Elements before i and
after j must remain Alternative implementation:
unchanged. items[i:j] = sorted(items
[i:j], key=c)

c is a key function, see the


doc.
291 Remove sublist items[i:j] = [] copy(items[i:], items[j:])
items.slice!(i...j)
Delete all the elements for k, n := len(items)-j+i, len(items); k <
from index i (included) to Alternative implementation: n; k++ {

index j (excluded) from items[k] = nil

del items[i:j]
the list items. }

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 print('Hello World and \u puts "Hello World and 你好"
Chinese to standard 4f60\u597d')

output in UTF-8
Write "Hello World and
你好" to standard output
in UTF-8.

You might also like