Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet
Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet
Go
Rust
Python
Kotlin
Scala
Dart
1 Print Hello World import "fmt" println!("Hello World"); print("Hello World") println("Hello wo println("Hello, Worl print("Hello Worl
Print a literal string on standard output rld!") d!") d");
fmt.Println("Hello World")
Alternative implementation:
package main
Alternative implementation:
func main(){print("Hello World")}
import __hello__
2 Print Hello 10 times import "fmt" for _ in 0..10 { println! for _ in range(10):
(0..9).forEach {
(0 until 10).foreach( print("Hello\n" *
Loop to execute some code a constant number ("Hello"); } print("Hello") println("Hell _ => println("Hell 10);
iterator.
}
a new line 10 times
}
at(10)); }
Alternative
implementation:
for(x in 1..10) {
println("Hel
lo")
thus has only side effects (e.g. Print to standard func finish(name string) {
The actual return type is Unit, braces will be replaced by its dbye $name")
${name}")
e $name.");
}
typed '()' and can be omitted value. This is called "f-strings" } } }
There is no return type in the signature, before the
from function signature. introduced in Python version
{.
3.6
Alternative implementation:
import "fmt"
This is a closure.
Alternative implementation:
def square(x):
return x**2
}
class Point:
Alternative
x: float
Point(this.x, th
from collections import n
is.y);
amedtuple
}
Point = namedtuple("Poin
With constructor,
t", "x y")
which you will almost
always have.
6 Iterate over list values for _, x := range items {
for x in items {
for x in items:
items.forEach { d items.foreach{doSomet items.forEach(doSo
Do something with each item x of an array-like doSomething(x)
do_something(x);
doSomething( x ) oSomething(it) } hing(_)} mething);
collection items, regardless indexes. } }
You have to explicitly ignore the index loop Alternative Alternative
variable, with the blank identifier _ Alternative implementation: implementation: implementation:
items.into_iter().for_each items.forEach(::d items.foreach(doSomet
(|x| do_something(x)); oSomething) hing)
Using a function when the method you're
reference. calling on each item in
the collection only takes a
Alternative single parameter, you can
implementation: omit specifying it.
for (x in items)
doSomething(x) Alternative
implementation:
for {
x <- items
} doSomething(x)
Go
Rust
Python
Kotlin
Scala
Dart
7 Iterate over list indexes and values import "fmt" for (i, x) in items.iter(). for i, x in enumerate(ite items.forEachInde val items = List("a", for (var i = 0; i
Print each index i with its value x from an array- enumerate() {
ms):
xed { i, x ->
"b", "c")
< items.length; i+
like collection items for i, x := range items {
fmt.Printf("Item %d = %v \n", i, x)
{}", i, x);
=$x")
reach{ case (item, in print('index=$i,
}
} } dex) =>
value=${items
The range clause gives you index i and value x at println(s"$index => [i]}');
r_each(|(i, x)| {
zipWithIndex takes each Alternative
println!("Item {} = item in a collection and implementation:
{}", i, x);
replaces it with a tuple of items.asMap().forE
}) (item, index) ach((i, value) {
print('index=$i,
value=$value');
});
Create a new map object x, and provide some Map; 2} e" to 1, "two" to "b" -> 2, "c" -> 3) "one": 1,
x.insert("one", 1);
isn't critical. See the
x.insert("two", 2); docs.
val x = mutableMa
pOf<String, Int>
The function new of the type
().apply {
}
Maps in Rust are generic and
type safe at compile time.
Alternative
Alternative implementation: implementation:
use std::collections::HashM val x = mutableMa
ap; pOf<String, Int>
()
x["two"] = 2
("one", 1),
("two", 2),
].into_iter().collect();
Go
Rust
Python
Kotlin
Scala
Dart
9 Create a Binary Tree data structure type BinTree struct {
struct BinTree<T> {
class Node:
data class Node(
class Node<T> {
child and right child are binary trees too. A node Left *BinTree
left: Option<Box<BinTre f, data):
val left: Nod Node<T> left, ri
has access to children nodes, but not to its Right *BinTree
e<T>>>,
self.data e? = null,
ght;
parent. }
right: Option<Box<BinTr = data
val right: No Node(this.value,
ee<T>>>,
self.left de? = null
{this.left, this.r
} = None
) ight});
self.righ }
t = None
Alternative implementation:
class Node:
self.data = data
self._left_child = le
ft_child
self._right_child = r
ight_child
Go
Rust
Python
Kotlin
Scala
Dart
10 Shuffle a list import "math/rand" extern crate rand;
from random import shuffl mutableList.shuff import scala.util.Ran x.shuffle();
Generate a random permutation of the elements use rand::{Rng, StdRng}; e le() dom
for i := range x {
This alters the content
of list x
j := rand.Intn(i + 1)
let mut rng = StdRng::new shuffle(x) Only mutable lists val items = List(1, of x.
x[i], x[j] = x[j], x[i]
().unwrap();
can be shuffled in- 2, 3, 4, 5)
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"
})
Last argument is a swap func.
Alternative implementation:
import "math/rand"
j := rand.Intn(i + 1)
}
Go
Rust
Python
Kotlin
Scala
Dart
11 Pick a random element from a list import "math/rand" use rand::{self, Rng}; import random list.random() import scala.util.Ran x[new Random().nex
List x must be non-empty. dom tInt(x.length)];
x[rand.Intn(len(x))] x[rand::thread_rng().gen_ra random.choice(x)
nge(0..x.len())] val x = List(1, 2, 3,
Alternative implementation: gen_range returns a number 4)
}
use rand::seq::SliceRandom; x(Random.nextInt(x.size))
If you decide to implement pickT, you will have to
write it separately for each desired type T. let mut rng = rand::thread_
rng();
Alternative implementation:
You may use any type T compatible with operator (&list).into_iter().any(|v|
== v == &x)
This is the the truly general
version, but it isn't the most
idiomatic.
13 Iterate over map keys and values import "fmt" use std::collections::BTree for k, v in mymap.items mymap.entries.for val x = Map("a" -> 1, mymap.forEach((k,
Access each key k with its value x from an Map; ():
Each { print("${i "b" -> 2, "c" -> 3)
v) => print('Key=
associative array mymap, and print them. for k, x := range mymap {
15 Pick uniformly a random integer in [a..b] import "math/rand" extern crate rand;
import random fun pick(a: Int, import util.Random import 'dart:mat
Pick a random integer greater than or equals to use rand::distributions::{I b: Int): Int {
h';
a, inferior or equals to b. Precondition : a < b. func pick(a,b int) int {
random.randint(a,b) a + Random.nextInt(b
ndependentSample, Range}; return (a..
return a + rand.Intn(b-a+1)
Upper bound b is included. + 1) int pick(int a, in
b).random()
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())
bt.Left.Dfs(f)
f(bt)
traverse(bt.lef
f(bt)
dfs(bt.right) t, f);
bt.Right.Dfs(f)
Recursive DFS. f(bt.value);
} traverse(bt.rig
The function f is a parameter of the traversal ht, f);
method Dfs. }
}
e
Node(this.value,
keyType should be easily comparable.
self.children = l this.children);
current node.
}
}
t:
for (var child i
f(t)
DFS(f, ch n node.children) {
}
self, f: F) {
}
} self.dfs_helper(& }
The function f is a parameter of the traversal f);
method Dfs .
}
(f)(&self.value);
child.dfs_helpe
r(f)
// ...
}
The actual idiomatic way to do
this is to implement an iterator.
Go
Rust
Python
Kotlin
Scala
Dart
19 Reverse a list for i, j := 0, len(x)-1; i < j; i, j = i+1, let y: Vec<_> = x.into_iter x = reversed(x) x.reverse() val items = List(1, x = x.reversed.toL
Reverse the order of the elements of list x.
j-1 {
().rev().collect(); 2, 3, 4, 5)
ist();
returns an iterable.
MutableLists or
This may reverse "in-place" and destroy the x[i], x[j] = x[j], x[i]
items.reverse
x is left unchanged.
on lists this creates a new list. Arrays can be
original ordering. } reversed in place.
This loop reverts "in-place" (in the original list, not Works with other data structures Alternative implementation:
creating a new one). that implement Iterator. y = x[::-1] Alternative
implementation:
Creates a new, reversed list.
Alternative implementation: x.reversed()
x.reverse(); Alternative implementation: Immutable lists but
x has type Vec.
x.reverse() not in-place.
Reverses list in place
This reverses in place. Alternative
implementation:
val reversedView
= x.asReversed()
Returns a reversed
read-only view of the
original List. All
changes made in the
original list will be
reflected in the
reversed one.
20 Return two values func search(m [][]int, x int) (bool, int, i fn search<T: Eq>(m: &Vec<Ve def search(m, x):
fun search(m: Arr def search[T](m: Iter class Position {
x in a 2D matrix m.
for i := range m {
ize, usize)> {
erate(m):
x: Int): Pair<In T): Option[(Int, In Position(this.i,
Return indices i, j of the matching cell.
for j, v := range m[i] {
for (i, row) in m.iter if x in item:
t, Int>? {
t)] = {
this.j);
to return the two values at the same time. return tru for (j, column) in tem.index(x) xed { i, row ->
view.zipWithIndex; (c Position search(Li
e, i, j
row.iter().enumerate() {
row.forEa olumn, j) <- row.vie st<List> m, x) {
}
if *column == * chIndexed { j, va w.zipWithIndex if col for (var i = 0;
}
x {
lue ->
umn == x)
i < m.length; i++)
}
return Some if (v return Some((i, {
return false, 0, 0
((i, j));
alue == x) {
j))
var line = m
} }
r None
[i];
None
}
if (line[j]
} return null
== x) {
return null;
}
Go
Rust
Python
Kotlin
Scala
Dart
21 Swap values a, b = b, a std::mem::swap(&mut a, &mut a, b = b, a a = b.also { b = val tmp = a
var tmp = a;
b = tmp
b = tmp;
Alternative implementation:
let (a, b) = (b, a);
This uses pattern matching and
destructuring of tuples to swap
values.
22 Convert string to integer import "strconv" let i = s.parse::<i32>().un i = int(s) val i = s.toInt() s.toInt var i = int.parse
Extract the integer value i from its string wrap(); (s);
representation s (in radix 10) i, err := strconv.Atoi(s)
This panics if s is not a valid Alternative
Atoi(s) is shorthand for ParseInt(s, 10, 0). It yields implementation:
number.
type int.
s is parsed to 32-bits signed val i = s.toIntOr
Alternative implementation: integer here (change number Null()
type if needed). i is null if s can not
import "strconv"
be converted to an
i, err := strconv.ParseInt(s, 10, 0) Alternative implementation:
integer
Radix 10. Third argument 0 means "fit in let i: i32 = s.parse().unwr
implementation-specific int". But result type is ap_or(0);
always int64.
This explicitly sets the value to 0
Don't ignore the potential error err ! if it can't be parsed to an integer.
Alternative implementation:
let i = match s.parse::<i32
>() {
Ok(i) => i,
};
s is parsed to 32-bits signed
integer here (change number
type if needed).
l;
Alan" v := <-ch
sendPort.send("val
fmt.Printf("Hello, %v\n", v)
let (send, recv) = channel t = Thread(target=worker)
ue");
}()
();
t.daemon = True
Ports are used for
t.start()
communicating
ch <- "Alan" thread::spawn(move || {
between individually
The receiver goroutine blocks reading the chan loop {
q.put("Alan") running isolates. The
string named ch.
let msg = recv.recv The Queue module has been receiving isolate has
The current goroutine sends the value to ch.
().unwrap();
renamed to queue in Python 3. created the
A goroutine is like a lightweight green thread. println!("Hello, corresponding
{:?}", msg);
receive-port and
}
passed the send-port
});
to this isolate.
send.send("Alan").unwrap();
The message might not be
printed if the main thread exits
before the thread has written to
stdout.
26 Create a 2-dimensional array const m, n = 3, 4
let mut x = vec![vec![0.0f6 x = [[0] * n for _ in ran val x = Array(m, val x = Array.ofDim[D var x = new List.g
Declare and initialize a matrix x having m rows var x [m][n]float64 4; N]; M]; ge(m)] { DoubleArray(n) ouble](m,n) enerate(m, (_) =>
and n columns, containing real numbers. })
new List(n));
m, n must be constant for this syntax to be valid.
Do not just "multiply by m",
Here x is of type [3][4]float64, it is not a slice. Alternative implementation: which would duplicate the The type of x is
let mut x = [[0.0; N] ; M]; references to the inner arrays. Array<DoubleArray>.
Alternative implementation: In other words, an
This works only when M and N
func make2D(m, n int) [][]float64 {
Alternative implementation: array of arrays.
are constant.
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.
Stack-allocated array.
x = numpy.zeros((m,n,p))
x := make([][][]float64, m)
growable: false),
for i := range x {
NumPy is a third-party library gr
M, N, P are constants.
x[i] = make([][]float64, n)
for scientific computing. owable: false);
for j := range x[i] {
Dart does not have
x[i][j] = buf[:p:p]
multidimensional
buf = buf[p:]
arrays as a primitive,
}
this is a list of lists of
}
lists of doubles, all
return x
fixed-length lists.
}
This works even when m, n, p are not compile-time
constants.
items.sortBy(_.x) (b.p));
Alternative implementation:
func sortItems(items []Item){
sorter := ItemPSorter(items)
from operator import attr
sort.Sort(sorter)
getter
} items = sorted(items, key
The standard way is to declare a new type =attrgetter('p'))
ItemSorter as a slice of Item, and carefully We use attrgetter to avoid
implement method Less. having to write a lambda. The
Operator module contains lots
Alternative implementation:
of useful functions that can be
import "sort"
passed to higher-order
less := func(i, j int) bool {
functions.
return items[i].p < items[j].p
sort.Slice(items, less)
This is the diomatic way since Go 1.8.
Go
Rust
Python
Kotlin
Scala
Dart
29 Remove item from list, by its index items = append(items[:i], items[i+1:]...) items.remove(i) del items[i] items.removeAt(i) items.removeAt(i);
Remove i-th item from list items.
If items elements are pointers or structs with This alters the original list.
This will alter the original list or return a new list,
pointers, then refer to the SliceTricks page to avoid
depending on which is more idiomatic.
memory leaks.
Note that in most languages, the smallest valid
value for i is 0. Alternative implementation:
copy(items[i:], items[i+1:])
items[len(items)-1] = nil
items = items[:len(items)-1]
This code is for pointer value type, and has no
memory leak.
30 Parallelize execution of 1000 independent import "sync" use std::thread; from multiprocessing impo import kotlinx.co
tasks rt Pool routines.*
Launch the concurrent execution of procedure f wg := sync.WaitGroup{}
let threads: Vec<_> = (0..1
with parameter i from 1 to 1000.
wg.Add(1000)
000).map(|i| {
pool = Pool()
fun main() = runB
Tasks are independent and f(i) doesn't return any for i := 1; i <= 1000; i++ {
thread::spawn(move for i in range(1, 1001):
locking {
value.
go func(j int) {
|| f(i))
pool.apply_async repeat(1000)
Tasks need not run all at the same time, so you f(j)
}).collect();
(f, [i]) {
}(i)
for thread in threads {
f(it)
}
thread.join();
}
wg.Wait() } }
The current value of i is captured, and a goroutine If you don't join the threads, the }
is launched program will just exit and the
threads will be killed.
Alternative implementation:
extern crate rayon;
use rayon::prelude::*;
(0..1000).into_par_iter().f
or_each(f);
Requires the rayon crate.
(https://crates.io/crates/rayon)
Go
Rust
Python
Kotlin
Scala
Dart
31 Recursive factorial (simple) func f(i int) int {
fn f(n: u32) -> u32 {
def f(i):
fun f(i: Int): In def f(i: Int): Int =
f(i) => (i == 0) ?
Create the recursive function f which returns the if i == 0 {
if n < 2 {
if i == 0:
t = when (i) {
if (i > 1){
1 : i * f(i - 1);
factorial of the non-negative integer i, calculated return 1
1
return 1
0 -> 1
i * f(i-1)
from f(i-1) }
} else {
else:
else -> i * f } else{
return i * f(i-1)
n * f(n - 1)
return i * f(i-1) (i - 1)
1
} }
}
}
}
Alternative
Alternative implementation: implementation:
fn factorial(num: u64) -> u fun f(i: Int) = i
64 {
f (i == 0) 1 else
match num {
i * f(i - 1)
0 | 1 => 1,
_ => factorial(num
- 1) * num,
}
match arm for 0|1 checks if the
numbers are either 0 or 1
Go
Rust
Python
Kotlin
Scala
Dart
32 Integer exponentiation by squaring func exp(x, n int) int {
fn exp(x: u64, n: u64) -> u def exp(x, n):
fun exp(x: Int, def exp(x: Int, n: In int exp(int x, int
Create function exp which calculates (fast) the switch {
64 {
return x**n
n: Int): Int = wh t): Int {
n) {
value x power n.
case n == 0:
match n {
en {
if(n == 0) {
if (n == 0) retu
x and n are non-negative integers. return 1
0 => 1,
n == 0 -> 1
1
rn 1;
case n == 1:
1 => x,
n == 1 -> x
} else if(n == 1) {
if (n == 1) retu
return x
i if i % 2 == 0 => n % 2 == 0 -> x
rn x;
case n%2 == 0:
exp(x * x, n / 2),
exp(x * x, n / 2)
} else if(n%2 == 0) var r = exp(x *
return exp(x*x, n/2)
_ => x * exp(x * x, else -> x * e {
x, n ~/ 2);
default:
(n - 1) / 2),
xp(x * x, (n - 1) exp(x*x, n/2)
if (n % 2 == 1)
return x * exp(x*x, (n-1)/ }
/ 2)
} else {
r *= x;
2)
} } x * exp(x*x, (n- return r;
}
1)/2)
}
} }
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.
lock.Unlock() x = f(x)
lock.release()
Alternative implementation:
import threading
with threading.Lock():
x = f(x)
But it is less intuitive to use than a bool value. s = set(T() for _ in rang
e(x))
36 First-class function : generic composition func composeIntFuncs(f func(int) int, g fun fn compose<'a, A, B, C, G, def compose(f, g):
compose(f, g) =>
Implement a function compose which returns c(int) int) func(int) int {
F>(f: F, g: G) -> Box<Fn(A) return lambda x: (x) => g(f(x));
composition function g ∘ f for any functions f and return func(x int) int {
-> C + 'a>
g(f(x))
g having exactly 1 parameter. return g(f(x))
where F: 'a + Fn(A) This is the same as for non-
}
-> B, G: 'a + Fn(B) -> C
generic composition
} {
}
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 {
}
Go
Rust
Python
Kotlin
Scala
Dart
37 Currying type PayFactory func(Company, *Employee, *E fn add(a: u32, b: u32) -> u from functools import par def add(x: Int)(y: In
Transform a function that takes multiple mployee) Payroll
32 {
tial t) = x + y
Alternative implementation:
use substring::Substring;
39 Check if string contains a word import "strings" let ok = s.contains(word); ok = word in s val ok = s.contai val ok = s.contains(w var ok = s.contain
Set boolean ok to true if string word is contained ns(word) ord) s(word);
in string s as a substring, or to false otherwise. ok := strings.Contains(s, word)
s and word have type Argument of contains
java.lang.String must be a Pattern.
Go
Rust
Python
Kotlin
Scala
Dart
40 Graph with adjacency lists type Vertex struct{
from collections import d inline class Vert
Declare a Graph data structure in which each Id int
efaultdict exId(val id: Int)
Neighbours map[*Vertex]bool
(val id: VertexI
class Graph(defaultdict):
}
d, val neighbour
def __init__(self, *pat
s: Set<VertexId>)
hs):
self.make_path(pat
h)
self[l1].add(l2)
self[l2].add(l1)
G = Graph((0, 1, 2, 3),
(1, 4, 2))
Go
Rust
Python
Kotlin
Scala
Dart
42 Continue outer loop mainloop:
'outer: for va in &a {
for v in a:
main() {
}
println!("{}", va);
except Exception:
for (var w in
fmt.Println(v)
}
continue
b) {
} 'outer is a label used to refer to Note that using two loops like if (w == v)
mainloop is a label used to refer to the outer loop. the outer loop. Labels in Rust this in python is by itself very continue outer;
exceptions. }
break mainl }
for column in m[r if (m[i][j] <
oop
}
ow]:
0) {
}
} if m[row][col print("Negat
}
Loop label syntax is similar to umn] == v:
ive value found at
} lifetimes. position $i,$j: ${m[i]
mainloop is a label used to refer to the outer loop. = (row, column)
[j]}");
akOuterLoop
}
except BreakOuterLoop:
}
pass }
This is ugly because the
pythonic way to solve this
problem would be to refactor
so that one doesn't have to
break out of multiple loops.
See PEP3136
Alternative implementation:
Go
Rust
Python
Kotlin
Scala
Dart
def loop_breaking(m, v):
for j, value in e
numerate(row):
if value ==
v:
return
(i, j)
return None
print(loop_breaking(([1,
2,3],[4,5,6],[7,8,9]),
6))
Rather than set break flags, it
is better to refactor into a
function, then use return to
break from all nested loops.
Alternative implementation:
from itertools import cha
in
matrix = [[1,2,3],[4,-5,
6],[7,8,9]]
try:
print(next(i for i in
chain.from_iterable(matri
x) if i < 0))
except StopIteration:
pass
We make a generator that will
return negative values from a
list (and use
chain.from_iterable(matrix) to
lazily extract the values) and
only take one value from it with
the next function. The
generator will not continue until
we call next again.
Alternative
implementation:
import "dart:asyn
c";
Alternative implementation:
let t = s.chars().take(5).c
ollect::<String>();
47 Extract string suffix t := string([]rune(s)[len([]rune(s))-5:]) let last5ch = s.chars().cou t = s[-5:] var n = s.length;
handled.
48 Multi-line string literal s := `Huey
let s = "line 1
s = """Huey
val s =
val s = """line 1
var s = '''A
several lines of text, including newlines. Louie` line 3"; Louie""" This is my
line 3""" string''';
This is a raw string literal (not "interpreted"). multi-line st Triple simple quotes.
Alternative implementation: ring.
Alternative
let s = r#"Huey
""" implementation: Alternative
Dewey
val s = """line 1
implementation:
Louie"#; |line 2
var s = """A
} } } }
No need to write loop variables nor end condition.
Alternative
implementation:
for (;;) {
51 Check if map contains key _, ok := m[k] use std::collections::HashM k in m m.containsKey(k) m.contains(k) m.containsKey(k)
Determine whether map m contains an entry for ap;
ok is true if m contains a value for key k. The value returns a Boolean
key k
itself is ignored. m.contains_key(&k)
Same method name for
HashMap and BTreeMap.
52 Check if map contains value func containsValue(m map[K]T, v T) bool {
use std::collections::BTree v in m.values() m.containsValue m.valuesIterator.cont m.containsValue
Determine whether the map m contains an entry for _, x := range m {
Map; (v) ains(v) (v);
with the value v, for some key. if x == v {
}
Works the same for HashMap.
return false
}
You have to iterate explicitly. Also, this works only
for types K, T (not generic).
Go
Rust
Python
Kotlin
Scala
Dart
53 Join a list of strings import "strings" let y = x.join(", "); y = ', '.join(x)
val y = listOf val y = x.mkString y = x.join(', ');
Concatenate elements of string list x joined by (x).joinToString (",")
y := strings.Join(x, ", ") Note that join() used to be This works if x contains only
the separator ", " to create a single string y. (", ")
named connect() . strings.
This works only if x has type []string.
Alternative implementation:
y = ', '.join(map(str,
x))
This works even if some
elements in x are not strings.
54 Compute sum of integers s := 0
x.iter().sum() s = sum(x) val numbers = lis val s = x.sum() var s = x.fold(0,
Calculate the sum s of the integer list or array x. for _, v := range x {
tOf(1, 2, 3, 4)
(a, b) => a + b);
sum is a built-in function.
s += v
Alternative implementation: val sum = number
} let s = x.iter().sum::<i32> s.sum()
Such explicit loops are idiomatic in Go. ();
55 Convert integer to string import "strconv" let s = i.to_string(); s = str(i) val s = i.toStrin val s = i.toString var s = "$i";
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.
Tasks are independent and f(i) doesn't return any for i := 1; i <= 1000; i++ {
(move || f(i))).collect();
i * i
.map { i ->
value.
go func(i int) {
Coroutine
Tasks need not run all at the same time, so you f(i)
for t in threads {
with Pool(1000) as p:
Scope(Dispatcher
may use a pool.
wg.Done()
t.join();
p.map(func=f, ite s.Default).async
Wait for the completion of the 1000 tasks and }(i)
}
rable=range(1, 1001))
{
wg.Wait()
print('Finished') }
fmt.Println("Finished") }
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.
Alternative implementation:
import sys
line parameter, after the program name. x := os.Args[1] let first_arg = env::args x = sys.argv[1]
}
os.Args[0] is actually the executable name. ().skip(1).next();
argv[0] is the program name
Command line
let fallback = "".to_owned arguments are only
();
available as argument
let x = first_arg.unwrap_or to main.
(fallback);
The first CLI argument may not
be present. We fall back to an
empty string.
Alternative implementation:
use std::env;
let x = env::args().nth(1).
unwrap_or("".to_string());
We get the 1st element using the
nth method and we fallback to
an empty string if no arg was
found.
61 Get current date import "time" extern crate time; import datetime var d = DateTime.n
Assign to variable d the current date/time value, ow();
Alternative implementation:
use std::time::SystemTime;
let d = SystemTime::now();
Go
Rust
Python
Kotlin
Scala
Dart
62 Find substring position import "strings" let i = x.find(y); i = x.find(y) var i = x.indexOf
Set i to the first position of string y inside string x, (y);
i := strings.Index(x, y) i is an Option<usize>.
find returns the character
if exists.
.to_string() or .to_owned() to
Assume occurrences of y are not overlapping. -1 means "no limit on the number of replacements".
get a String.
This replaces non-overlapping instances of y.
64 Big integer : value 3 power 247 import "math/big" extern crate num;
x = 3 ** 247 import "dart:mat
Assign to x the value 3^247 use num::bigint::ToBigInt; h";
x := new(big.Int)
65 Format decimal number import "fmt" let s = format!("{:.1}%", 1 s = '{:.1%}'.format(x) var s = "${(x * 10
From the real value x in [0,1], create its 00.0 * x); 0).toStringAsFixed
.1 means only one digit after
percentage string representation s with one digit s := fmt.Sprintf("%.1f%%", 100.0*x) (1)}%";
decimal point.
after decimal point. E.g. 0.15625 -> "15.6%" The literal % must be doubled.
% handles the "multiplication"
and shows the percentage
sign.
Alternative implementation:
s = f"{x:.01%}"
66 Big integer exponentiation import "math/big" extern crate num; z = x**n import "dart:mat
Calculate the result z of x power n, where x is a h";
big integer and n is a positive integer. nb := big.NewInt(int64(n))
let z = num::pow(x, n);
var z big.Int
var z = pow(x, n);
z.Exp(x, nb, nil)
Exponentiation is already implemented in package
math/big.
Go
Rust
Python
Kotlin
Scala
Dart
67 Binomial coefficient "n choose k" import "math/big" extern crate num;
import math int binom(int n, i
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an nt k) {
use num::bigint::BigInt;
int result = 1;
// math.factorial(n - k)
result = resul
fn binom(n: u64, k: u64) ->
t * (n - i) ~/ (i
BigInt {
Alternative implementation:
+ 1);
ne();
for i in 0..k {
return math.comb(n, }
res = (res * (n -
i).to_bigint().unwrap()) /
k)
(i + 1).to_bi Python 3.8+
gint().unwrap();
res
68 Create a bitset import "math/big" let mut x = vec![false; n]; from __future__ import di
Create an object x to store n bits (n being vision
Alternative implementation:
x := make([]uint64, (n+63)/64)
This compact bitset requires some extra logic to
implement get, set, clear (see demo).
69 Seed random generator import "math/rand" use rand::{Rng, SeedableRn import random val random = Rand import "dart:mat
Use seed s to initialize a random generator.
g, rngs::StdRng}; om(seed=s) h";
rand.Seed(s) rand = random.Random(s)
If s is constant, the generator output will be the s is of type int64.
let s = 32;
this creates a new random var r = new Random
same each time the program runs. If s is based This initializes the default Source. let mut rng = StdRng::seed_ generator rand (s);
r := rand.New(rand.NewSource(s))
s is of type int64.
r is of type *rand.Rand.
Go
Rust
Python
Kotlin
Scala
Dart
70 Use clock as random generator seed import "math/rand"
use rand::{Rng, SeedableRn import random var r = new Random
Get the current datetime and provide it as a seed import "time" g, rngs::StdRng};
(new DateTime.now
to a random generator. The generator sequence rand = random.Random()
use std::time::SystemTime; ().millisecondsSin
will be different at each run. rand.Seed(time.Now().UnixNano()) the constructor uses the ceEpoch);
This initializes the default Source. let d = SystemTime::now()
current time if used without
.duration_since(SystemT arguments.
all arguments except the program name, println!("{}", env::args(). print ' '.join(sys.argv
import "strings" gs.forEach(::prin print(args.join
separated by space, followed by newline.
skip(1).collect::<Vec<_>> [1:])
tln) (' '));
println!("{}", std::env::ar
gs().skip(1).format(" "));
handle huge numbers. The first two arguments can be ignored in this use use num::bigint::BigInt; var t = b;
case.
b = a % t;
let x = a.gcd(&b);
a = t;
trait. return a;
}
Go
Rust
Python
Kotlin
Scala
Dart
75 Compute LCM import "math/big" extern crate num;
from math import gcd x = lcm(a, b);
while (b != 0) {
b = a % t;
return a;
76 Binary digits from an integer import "strconv" let s = format!("{:b}", x); s = '{:b}'.format(x) var s = x.toRadixS
Create the string s of integer x written in base 2.
tring(2);
s := strconv.FormatInt(x, 2) Formatting lets you choose
another representation (e.g., `b`
E.g. 13 -> "1101" Here x has the type int64.
Alternative implementation:
import "fmt"
import "math/big"
s := fmt.Sprintf("%b", x)
x has the type *big.Int.
break
Rust has no do-while loop with } while(c);
}
syntax sugar. Use loop and
} break.
Go has no do while loop, use the for loop, instead.
Alternative implementation:
Alternative implementation: while {
someThing()
c
someOtherThing()
} { /* EMPTY */ }
done = !c()
Use compound expression for
} the while loop condition.
Explicit loop variable done shows the intent.
79 Convert integer to floating point number y := float64(x) let y = x as f64; y = float(x) double y = x.toDou
Declare the floating point number y and initialize ble();
The cast must be explicit.
it with the value of the integer x .
There is no implicit
conversion so you
have to use toDouble
explicitly, or maybe
better: type y as num
which is the
superclass of double
and int.
80 Truncate floating point number to integer y := int(x) let y = x as i32; y = int(x) int y = x.toInt()
Declare integer y and initialize it with the value of
There is no automatic
floating point number x . Ignore non-integer digits
conversion, so you
of x .
have to explicitly call
Make sure to truncate towards zero: a negative x
toInt on the double.
must yield the closest greater integer (not lesser).
The toInt call
truncates, there are
also ceil, floor and
round methods.
81 Round floating point number to integer import "math" let y = x.round() as i64; y = int(x + 0.5) var y = x.round();
i &= 0x0f0f0f0f0f0f0f0f
i *= 0x0101010101010101
i += i >> 4
i &= 0x0f0f0f0f
i *= 0x01010101
}
This was useful only before go 1.9.
Alternative implementation:
import "math/bits"
c := bits.OnesCount(i)
i is a uint.
which takes two integers x, y and return true if func addingWillOverflow(x int, y int) bool
x.checked_add(y).is_non return False
(x+y) overflows.
{
e()
Python has arbitrary precision
if x > 0 {
}
checked_add is available for all about overflow.
Err(CustomError::In
validAnswer)
} else {
Ok(x)
}
A function that can have invalid
inputs should not panic, but
return a Result. The calling
function can then determine
whether to handle the Err value
or unwrap the Result and turn
every Err into a panic.
Go
Rust
Python
Kotlin
Scala
Dart
90 Read-only outside type Foo struct {
struct Foo {
class Foo(object):
Foo.
func (f *Foo) X() int {
impl Foo {
@property
return f.x
pub fn new(x: usize) -> def x(self):
} Self {
"""
return self._x
pub fn x<'a>(&'a self)
-> &'a usize {
&self.x
self.x += 1;
r, err := os.Open(filename)
Map x = json.jsonD
if err != nil {
ecode(new File('da
return err
ta.json').readAsSt
}
ringSync());
decoder := json.NewDecoder(r)
x is a Map
err = decoder.Decode(&x)
if err != nil {
return err
}
Create and use a *json.Decoder
Go
Rust
Python
Kotlin
Scala
Dart
92 Save object into JSON file import "encoding/json"
extern crate serde_json;
import json import 'dart:io' s
Write the contents of the object x into the file import "io/ioutil" #[macro_use] extern crate s how File;
return err
::serde_json::to_writer(&Fi // Create Field
}
le::create("data.json")?, & int id;
// JsonModel(
// int idIn
t, String nameStri
ng, String userStr
ing, String passwo
rdString) {
// // id=idIn
t;
// // name =nameSt
ring;
// // user =userSt
ring;
// // password = p
asswordString;
// }
JsonModel(this.i
d, this.name, thi
s.licen, this.tran
s, this.qrText);
JsonModel.fromJs
on(Map<String, dyn
amic> parseJSON) {
id = int.parse
(parseJSON['id']);
licen = parseJ
SON['Li
x is a Map
93 Pass a runnable procedure as parameter func control(f func()) {
fn control(f: impl Fn()) {
from __future__ import pr
Implement procedure control which receives one f()
f();
int_function
parameter f, and runs f. } }
def control(f):
fmt.Printf("%T", x) ame::<T>()
println!("{}", type_of(&
x));
As of 2020-09 this is a nightly-
only experimental API.
95 Get file size import "os" use std::fs; import os import 'dart:io';
Assign to variable x the length (number of bytes)
of the local file at path. info, err := os.Stat(path)
let x = fs::metadata(pat x = os.path.getsize(path) final x = (await F
if err != nil {
h)?.len(); ile(path).readAsBy
return err
tes()).length;
}
Alternative implementation:
x := info.Size() let x = path.metadata()?.le Alternative
info has type os.FileInfo . n(); implementation:
96 Check string prefix import "strings" let b = s.starts_with(prefi b = s.startswith(prefix) val b = s.startsW val b = s.startsWith var b = s.startsWi
Set boolean b to true if string s starts with prefix x); ith(prefix) (prefix) th(prefix);
prefix, false otherwise. b := strings.HasPrefix(s, prefix)
97 Check string suffix import "strings" let b = s.ends_with(suffi b = s.endswith(suffix) b = s.endsWith(su val b = s.endsWith(su var b = s.endsWith
Set boolean b to true if string s ends with string x); ffix) ffix) (suffix);
suffix, false otherwise. b := strings.HasSuffix(s, suffix)
let x = d.format(&format).e
xpect("Failed to format the
date");
time crate is better maintained.
Go
Rust
Python
Kotlin
Scala
Dart
100 Sort by a comparator import "sort" items.sort_by(c); items.sort(key=c) items.sortWith(c)
Sort elements of array-like collection items,
type ItemCSorter []Item
c is a key function, see the
using a comparator c.
func (s ItemCSorter) Len() int { doc.
return len(s) }
Alternative implementation:
func (s ItemCSorter) Less(i, j int) bool {
return c(s[i], s[j]) }
import functools
func (s ItemCSorter) Swap(i, j int) { items.sort(key=functools.
s[i], s[j] = s[j], s[i] }
cmp_to_key(c))
c is an old-style comparison
func sortItems(items []Item) {
function
sorter := ItemCSorter(items)
sort.Sort(sorter)
}
c has type func(Item, Item) bool.
Alternative implementation:
import "sort"
items []Item
sorter := ItemsSorter{
items,
c,
sort.Sort(sorter)
}
ItemsSorter contains c, which can be any
comparator decided at runtime.
Alternative implementation:
import "sort"
})
Since Go 1.8, a single func parameter is sufficient
to sort a slice.
Go
Rust
Python
Kotlin
Scala
Dart
101 Load from HTTP GET request into a string import "io/ioutil"
extern crate reqwest;
import urllib.request
val s = scala.io.Sour
Make an HTTP request with method GET to URL import "net/http" use reqwest::Client; ce.fromURL(u).getLine
u, then store the body of the response in string s. with urllib.request.urlop
s().mkString("\n")
res, err := http.Get(u)
let client = Client::new();
en(u) as f:
if err != nil {
let s = client.get(u).send s = f.read()
return err
().and_then(|res| res.text
}
())?;
buffer, err := ioutil.ReadAll(res.Body)
res.Body.Close()
Alternative implementation:
if err != nil {
[dependencies]
return err
ureq = "1.0"
}
Alternative implementation:
It is idiomatic and strongly recommended to check
[dependencies]
use error_chain::error_chai
n;
use std::io::Read;
response.read_to_string(&mu
t s)?;
This is a synchronous
(blocking) reqwest call.
u, then store the body of the response in file filename, headers = urlli
import "net/http" use std::fs::File;
result.txt. Try to save the data as it arrives if b.request.urlretrieve(u,
possible, without having all its content in memory resp, err := http.Get(u)
let client = Client::new();
'result.txt')
}
Ok(res) => {
defer resp.Body.Close()
let file = File::cr
if resp.StatusCode != 200 {
eate("result.txt")?;
}
},
}
};
defer out.Close()
if err != nil {
return err
}
resp has type *http.Response.
if err != nil {
return err
}
buffer is a []byte.
Write the contents of the object x into the file import "io/ioutil"
data.xml.
buffer, err := xml.MarshalIndent(x, "", "
")
if err != nil {
return err
path := os.Args[0]
sys.argv[0] holds the name of
.ok()
fn main() -> () {
let s = get_exec_name
().unwrap();
println!("{}", s);
Alternative implementation:
let s = std::env::current_e
xe()
.file_name()
.to_string_lossy()
.into_owned();
106 Get program working directory import "os" use std::env; import os
Assign to string dir the path of the working
directory.
dir, err := os.Getwd() let dir = env::current_dir dir = os.getcwd()
(This is not necessarily the folder containing the ().unwrap(); getcwd stands for Get the
executable itself) dir has type PathBuf Current Working Directory
107 Get folder containing current program import "os"
let dir = std::env::current import os
Assign to string dir the path of the folder import "path/filepath" _exe()?
th)
.parent()
if err != nil {
.expect("the current ex
return err
e should be a file")
.to_string_lossy()
dir := filepath.Dir(absolutePath)
.to_owned();
Rust doesn't represent paths as
Strings, so we need to convert
the Path returned from
Path::parent. This code chooses
to do this lossily, replacing
characters it doesn't recognize
with �
Go
Rust
Python
Kotlin
Scala
Dart
108 Determine if variable name is defined if 'x' in locals():
except NameError:
109 Number of bytes of a type import "reflect" let n = ::std::mem::size_o import pympler.asizeof
Set n to the number of bytes of a variable t (of f::<T>();
type T). var t T
n = pympler.asizeof.asize
tType := reflect.TypeOf(t)
n is "the offset in bytes between of(t)
n := tType.Size() successive elements in an array
`pip install pympler` to get this
with item type T"
This run-time reflection works on a value of the third-party library.
type T.
`sys.getsizeof` is built-in, but
Note that the size does not include the memory has many common failure
indirectly taken by the reference fields: Strings, modes.
slices, etc.
.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;
.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;
.args(&["a", "b"])
.status()
.expect("failed to
execute process");
status() waits for x to complete
and collects its exit status
112 Iterate over map entries, ordered by keys import "fmt"
for (k, x) in mymap {
for k in sorted(mymap):
import scala.collecti
Print each key k with its value x from an import "sort" println!("({}, {})", k, print(mymap[k])
on.immutable.SortedMa
associative array mymap, in ascending order of x);
p
keys := make([]string, 0, len(mymap))
dictionaries iterate over their
k. }
for k := range mymap {
keys by default SortedMap.from(myma
keys = append(keys, k)
This assumes mymap is a p).foreach{ case (k,
}
BTreeMap as it is sorted by the x) => println(s"$k =>
sort.Strings(keys)
keys. $x") }
x := mymap[k]
}
First extract the keys, then sort them, then iterate.
x.
println!("[{},{}]", print(k, x)
Note that multiple entries may exist for the same type entry struct {
k, x);
import operator
}
Requires the itertools crate
for key, value in sorted
Alternative implementation:
type entries []entry
(d.items(), key=operator.
func (list entries) Len() int { return len let mut items: Vec<_> = mym itemgetter(1)):
(list) }
ap.iter().collect();
print(key, value)
func (list entries) Less(i, j int) bool { r items.sort_by_key(|item| it
operator.itemgetter(1) gets the
eturn list[i].value < list[j].value }
em.1);
returned by d.items()
[i], list[j] = list[j], list[i] }
println!("[{},{}]", k,
x);
sort.Sort(entries)
}
Define custom types entry and entries.
Alternative implementation:
import "fmt"
import "sort"
key string
value int
})
}
Go
Rust
Python
Kotlin
Scala
Dart
Using sort.Slice incurs slightly less boilerplate than
sort.Sort.
114 Test deep equality import "reflect" let b = x == y; b = x == y case class A(a: Int,
Set boolean b to true if objects x and y contain b: Float, c: String)
Tell if the code correctly handles recursive types. DeepEqual correctly handles recursive types. val y = A(1,2.2f,"hel
All objects in the standard
library do so. lo")
b = x == y
Alternative implementation:
Replaces w with empty string. -1 means "replace
let s2 = str::replace(s1,
all occurrences".
w, "");
Alternative implementation:
import "strings"
s2 := strings.ReplaceAll(s1, w, "")
x = x2
Original order is preserved.
Go
Rust
Python
Kotlin
Scala
Dart
This is O(n).
Alternative implementation:
seen := make(map[T]bool)
j := 0
for _, v := range x {
if !seen[v] {
x[j] = v
j++
seen[v] = true
x = x[:j]
The order is preserved.
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[i] = nil
x = x[:j]
Order is preserved.
This is O(n).
120 Read integer from stdin import "fmt" fn get_input() -> String {
n = int(input("Input Prom
Read an integer value from the standard input let mut buffer = Strin pting String: "))
into the variable n _, err := fmt.Scan(&n)
g::new();
Alternative implementation:
buffer
import "fmt"
}
Alternative implementation:
use std::io;
io::stdin().read_line(&mut
input).unwrap();
Alternative implementation:
use std::io::BufRead;
.lock()
.lines()
.next()
.expect("stdin should b
e available")
.expect("couldn't read
from stdin")
.trim()
.parse()
Alternative implementation:
#[macro_use] extern crate t
ext_io;
4];
et.AF_INET, socket.SOCK_D
"os"
)
(("localhost", p)).unwrap sock.bind((UDP_IP, p))
p)
sock.recv_from(&mut b).unwr data, addr = sock.rec
if err != nil {
ap(); vfrom(1024)
return err
print("received messa
}
ge:", data)
ServerConn, err := net.ListenUDP("udp", Ser Buffer size is 1024 bytes
verAddr)
if err != nil {
return err
defer ServerConn.Close()
n,addr,err := ServerConn.ReadFromUDP(b[:102
4])
if err != nil {
return err
if n<1024 {
Diamonds
} }
Clubs
Alternative implementation:
) from enum import Enum
Go doesn't have enumerations.
class Suit(Enum):
HEARTS = 2
DIAMONDS = 3
CLUBS = 4
New in Python 3.4
Go
Rust
Python
Kotlin
Scala
Dart
123 Assert condition if !isConsistent() {
assert!(is_consistent); assert isConsistent assert(isConsisten
Verify that predicate isConsistent returns true, panic("State consistency violated")
t)
raises AssertionError
otherwise report assertion violation.
} Exception.
Needs to be executed
Explain if the assertion is executed even in
Go doesn't provide assertions.
with "--enable-asserts"
production environment or not.
But it's still possible to crash when desired. Running Python with option _- flag with dart and
O or with PYTHONOPTIMZE
dart2js commands.
dartdevc
(development
compiler) will execute
it by default.
Go
Rust
Python
Kotlin
Scala
Dart
124 Binary search for a value in sorted array func binarySearch(a []T, x T) int {
a.binary_search(&x).unwrap_ import bisect def binarySearch(a
Write the function binarySearch which returns imin, imax := 0, len(a)-1
or(-1); r, el)
the index of an element having the value x in the def binarySearch(a, x):
t(a, x)
/ 2
Generally, a Result or Option res ? res : -1
return i if i != len
switch {
would be more useful. end
(a) and a[i] == x else -1
case a[imid] == x:
return imid
imin = imid + 1
default:
imax = imid - 1
return -1
}
Iterative algorithm.
Alternative implementation:
import "sort"
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.
Alternative implementation:
import "sort"
i := sort.Search(len(a), f)
return i
return -1
}
This uses the standard library generic-purpose
sort.Search. Read the documentation carefully.
t := time.Since(t1)
foo();
foo()
ns := int64(t / time.Nanosecond)
let duration = start.elapse t2 = time.perf_counter_ns
fmt.Printf("%dns\n", ns) d();
()
t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)
t1 has type time.Time.
} fun useFoo() {
val a, b = foo
()
o
"foobody.txt" must contain a
To remove all side-effects: del
single Rust expression. If you
sys.modules['foobody']
need several, enclose them in
braces.
Go
Rust
Python
Kotlin
Scala
Dart
128 Breadth-first traversing of a tree func (root *Tree) Bfs(f func(*Tree)) {
use std::collections::VecDe def BFS(f, root):
struct Tree<V> {
}
n = Q.pop
children: Vec<Tree<V>>,
queue := []*Tree{root}
(0)
value: V
t := queue[0]
for child
queue = queue[1:]
in n:
impl<V> Tree<V> {
f(t)
i
fn bfs(&self, f: impl F
queue = append(queue, t.Chi f not n.discovered:
n(&V)) {
ldren...)
let mut q = VecDequ
}
n.discovered = True
e::new();
}
q.push_back(self);
q.push_back
(child);
f):
seen = set()
v := queue[0]
q = deque([start])
queue = queue[1:]
while q:
f(v)
vertex = q.popleft()
v.Neighbours {
seen.add(vertex)
ertex.adjacent if v not i
queue = app
n seen)
end(queue, next)
}
Bfs is a method of type *Vertex : the receiver is the
start node.
value: V,
neighbours: Vec<Wea
k<RefCell<Vertex<V>>>>,
// ...
fn bft(start: Rc<RefCell<Ve
rtex<V>>>, f: impl Fn(&V))
{
let mut i = 0;
let v = Rc::clo
ne(&q[i]);
i += 1;
(f)(&v.borrow
().value);
for n in &v.bor
row().neighbours {
let n = n.u
pgrade().expect("Invalid ne
ighbour");
if q.iter
().all(|v| v.as_ptr() != n.
as_ptr()) {
q.push
(n);
}
See demo for full example.
Go
Rust
Python
Kotlin
Scala
Dart
130 Depth-first traversing in a graph func (v *Vertex) Dfs(f func(*Vertex), seen use std::rc::{Rc, Weak};
def depth_first(start,
Call th function f on every vertex accessible from map[*Vertex]bool) {
use std::cell::RefCell; f):
struct Vertex<V> {
f(v)
stack = [start]
value: V,
neighbours: Vec<Wea
urs {
vertex = stack.pop()
k<RefCell<Vertex<V>>>>,
next.Dfs(f, seen)
seen.add(vertex)
}
stack.extend(
// ...
}
v for v in vertex.a
} djacent if v not in seen
fn dft_helper(start: Rc<Ref
Dfs is a method of type *Vertex : the receiver is the )
Cell<Vertex<V>>>, f: &impl
start node.
Fn(&V), s: &mut Vec<*const It's best to not recurse in
The function f is a parameter of the traversal Vertex<V>>) {
Python when the structure size
method.
s.push(start.as_ptr is unknown, since we have a
Start with an empty map as initial seen parameter. ());
fixed, small stack size.
(f)(&start.borrow
().value);
for n in &start.bor
row().neighbours {
let n = n.u
pgrade().expect("Invalid ne
ighbor");
if s.iter
().all(|&p| p != n.as_ptr
()) {
Sel
f::dft_helper(n, f, s);
}
See demo for full example.
Go
Rust
Python
Kotlin
Scala
Dart
131 Successive conditions switch {
if c1 { f1() } else if c2 { f1 if c1 else f2 if c2 el when {
true match {
if (c1) {
if c1:
match true {
f1()
f3()
_ if c1 => f1(),
elif c2:
()
}
} _ if c2 => f2(),
f2()
}
_ if c3 => f3(),
elif c3:
Using match with guards
_ => (),
f3()
} Alternative
implementation:
Using match and guards
if (c1) {
f1()
} else if (c2) {
f2()
} else if (c3) {
f3()
start = time.time()
f()
end = time.time()
use regex::RegexBuilder;
let re =
RegexBuilder::new(®e
x::escape(word))
.case_insensitive(true)
.build().unwrap();
let ok = re.is_match(s);
Alternative implementation:
let ok = s.to_ascii_lowerca
se().contains(&word.to_asci
i_lowercase());
134 Create a new list items := []T{a, b, c} let items = vec![a, b, c]; items = [a, b, c] val items = listO val items = List(a, var items = [a, b,
Declare and initialize a new list items, containing f(a, b, c) b, c) c];
This creates a slice of type T.
3 elements a, b, c.
Go
Rust
Python
Kotlin
Scala
Dart
135 Remove item from list, by its value for i, y := range items {
if let Some(i) = items.firs items.remove(x) items.remove(x);
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.
if v != x {
items[j] = items[i]
j++
items = items[:j]
This filters items in-place in linear time.
Alternative implementation:
j := 0
if v != x {
items[j] = items[i]
j++
items[k] = nil
items = items[:j]
This filters items in-place in linear time.
}
.collect();
Returns false if s is empty. Alternative
} let b = !chars_are_numeric. implementation:
c has type rune. contains(&false); fun String?.isOnl
Note that is_numeric is not just yDigits() = !thi
Alternative implementation: 0 -> 9. s.isNullOrEmpty()
import "strings" See documentation for more && this.all { Cha
info. racter.isDigit(i
isNotDigit := func(c rune) bool { return c
t) }
< '0' || c > '9' }
Alternative implementation:
b := strings.IndexFunc(s, isNotDigit) == -1 We can check all
let b = s.chars().all(cha characters by
r::is_numeric); string's all method,
without any regexp
Alternative implementation:
let b = s.bytes().all(|c|
c.is_ascii_digit());
only return true for ASCII digits
138 Create temp file import "io/ioutil" use tempdir::TempDir;
import tempfile
Create a new temporary file on the filesystem. use std::fs::File;
tmpfile, err := ioutil.TempFile("", "") file = tempfile.Temporary
tmpfile has type *os.File.
let temp_dir = TempDir::new File()
("prefix")?;
Alternative
implementation:
m -= k
This mutates the map m,
removing k from it. If k
doesn't exist in m, no
error occurs. Only
available on mutable
Map. The default
implementation of Map is
a HashMap.
141 Iterate in sequence over two lists for _, v := range items1 {
for i in item1.iter().chain for x in items1 + items2:
}
No magic sugar. Write 2 loops.
142 Hexadecimal digits of an integer import "strconv" let s = format!("{:X}", x); s = hex(x)
Assign to string s the hexadecimal representation
s := strconv.FormatInt(x, 16) {:X} produces uppercase hex.
import "math/big"
s := fmt.Sprintf("%x", x)
x has type *big.Int.
fmt.Println(items1[i])
println!("{}", pair.0);
min(len(item1), item(2)) pairs if
}
different size. }
fmt.Println(items2[i])
144 Check if file exists import "os" let b = std::path::Path::ne import os import java.io.Fi
Set boolean b to true if file at path fp exists on w(fp).exists();
le;
filesystem; false otherwise.
_, err := os.Stat(fp)
b = os.path.exists(fp)
b := !os.IsNotExist(err) b = File(fb).exis
Beware that you should never do this and then in There's no specific existence check func in Alternative implementation: ts()
the next instruction assume the result is still valid, standard library, so we have to inspect an error from pathlib import Path
this is a race condition on any multitasking OS. return value.
b = Path(fp).exists()
145 Print log line with datetime import "log" eprintln!("[{}] {}", humant import sys, logging
Print message msg, prepended by current date ime::format_rfc3339_seconds
and time.
log.Println(msg) logging.basicConfig(strea
(std::time::SystemTime::now
This prints to os.Stderr by default, with a datetime m=sys.stdout, level=loggi
()), msg);
Explain what behavior is idiomatic: to stdout or prefix. ng.DEBUG, format="%(ascti
Writes an RFC3339 date to me)-15s %(message)s")
logger.info(msg)
Default output is stderr.
Alternative implementation:
f = float(s)
Alternative implementation:
f = float(s)
Go
Rust
Python
Kotlin
Scala
Dart
147 Remove all non-ASCII characters import "regexp" let t = s.replace(|c: char| import re
Create string t from string s, keeping only ASCII !c.is_ascii(), "");
characters re := regexp.MustCompile("[[:^ascii:]]")
t = re.sub('[^\u0000-\u00
t := re.ReplaceAllLiteralString(s, "") 7f]', '', s)
Alternative implementation:
"unicode"
if r > unicode.MaxASCII {
return -1
return r
}, s)
"strconv"
} Alternative implementation:
)
let mut string = String::ne numbers = [int(x) for x i
var ints []int
w();
n input().split()]
s := bufio.NewScanner(os.Stdin)
io::stdin().read_to_string
s.Split(bufio.ScanWords)
(&mut string)?;
for s.Scan() {
let result = string
i, err := strconv.Atoi(s.Text())
.lines()
if err == nil {
.map(i32::from_str)
ints = append(ints, i)
.collect::<Result<Vec<_
}
>, _>>();
}
result is a Result<Vec<i32>,
if err := s.Err(); err != nil {
ParseIntError>.
return err
platform.
p = p[:-1]
&p[0..p.len()-1]
} else {
Note that this also transforms unix root path "/" p = strings.TrimSuffix(p, sep)
p
h::is_separator).unwrap_or
import "path/filepath"
(p);
import "strings"
p = strings.TrimSuffix(p, sep)
filepath.Separator is a rune, it must be converted
to string.
152 Turn a character into a string import "fmt" let s = c.to_string(); s = c val s: String =
Create string s containing only the character c. c.toString()
s := fmt.Sprintf("%c", c) a character is a single
character string, not a distinct c has type Char.
datataype
153 Concatenate string with integer import "fmt" let t = format!("{}{}", s, t = '{}{}'.format(s,i) val t = s + i
Create string t as the concatenation of string s i);
and integer i. t := fmt.Sprintf("%s%d", s, i)
Alternative implementation:
c, c1, c2 are strings of hex color codes: 7 chars, r1, _ := strconv.ParseInt(c1[1:3], 16, 0)
"Too long for text box, see
r2, g2, b2 = [int(c2[p:p+
beginning with a number sign # .
r2, _ := strconv.ParseInt(c2[1:3], 16, 0)
online demo"
2], 16) for p in range(1,
Assume linear computations, ignore gamma r := (r1 + r2) / 2
6,2)]
corrections. c = '#{:02x}{:02x}{:02
g1, _ := strconv.ParseInt(c1[3:5], 16, 0)
x}'.format((r1+r2) // 2,
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)
Alternative implementation:
b1, _ := strconv.ParseInt(c1[5:7], 16, 0)
@classmethod
def __str__(self):
buf[0] = '#'
self = self.astype(nu
for i := 0; i < 3; i++ {
mpy.uint8)
0)
1')
v := (v1 + v2) / 2
print(c1)
sub := fmt.Sprintf("%02X", v)
c2 = RGB.from_str('#1A1B1
copy(buf[1+2*i:3+2*i], sub)
C')
print(c2)
c := string(buf[:])
Loops over each component r, g, b.
print((c1 + c2) / 2)
numpy is standard for array
For conciseness this assumes that input validity
numerics, and works nicely for
has already been checked, so we omit some
this problem. We can represent
returned errors.
a RGB value as a special
numpy array.
155 Delete file import "os" use std::fs; import pathlib
Delete from filesystem the file having path
filepath. err := os.Remove(filepath) let r = fs::remove_file(fil path = pathlib.Path(_file
epath); path)
not.
The original ordering is not preserved.
159 Trie type Trie struct {
struct Trie {
class Trie:
} self.children = []
platform is 64-bit.
if strconv.IntSize==32 {
if sys.maxsize > 2**32:
4 => f32(),
8 => f64(),
_ => {}
if strconv.IntSize==64 {
f32()
}
f64()
fox();
if 'f' in sys.argv[1:]: f
} else if &arg = "b" {
func main() {
ox()
bat();
flag.Parse()
} else {
if *b {
Alternative implementation:
eprintln!("invalid
bar()
options = {
}
'b': bat
if *f {
'f': fox
} else {
fox()
}
eprintln!("missing argu
}
ment");
options as -b -f
Alternative implementation: if option in sys.
(with a dash). argv[1:]:
()
match arg.as_str() {
_ => eprintln!("inv
alid argument: {}", arg),
};
} else {
eprintln!("missing argu
ment");
}
Go
Rust
Python
Kotlin
Scala
Dart
163 Print list elements by group of 2 import "fmt" for pair in list.chunks(2) for x in zip(list[::2], l for (pair <- list.gro
Print all the list elements, two by two, assuming {
ist[1::2]):
uped(2))
ir[0], pair[1]);
original list is called list (0)}, ${pair(1)})")
}
}
Alternative implementation:
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for a, b in pairwise(lis
t):
print(a, b)
Official documentation
suggestion. Works for any
iterable
164 Open URL in the default browser import "github.com/skratchdot/open-golang/o use webbrowser; import webbrowser
Open the URL s in the default browser.
pen"
Set boolean b to indicate whether the operation webbrowser::open(s).expect webbrowser.open(s)
was successful. b := open.Start(s) == nil ("failed to open URL");
b is not available
Alternative implementation:
func openbrowser(url string) {
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-ope
n", url).Start()
case "windows":
err = exec.Command("rundll3
2", "url.dll,FileProtocolHandler", url).Sta
rt()
case "darwin":
err = exec.Command("open",
url).Start()
default:
err = fmt.Errorf("unsupport
ed platform")
if err != nil {
log.Fatal(err)
}
Go
Rust
Python
Kotlin
Scala
Dart
165 Last element of list x := items[len(items)-1] let x = items[items.len()- x = items[-1] var x = items.las val x = items.last x = items.last;
Assign to variable x the last element of list items. 1]; t()
items is a slice.
copy(ab[len(a):], b)
Alternative implementation:
let t = if s.starts_with(p)
{ &s[p.len()..] } else { s
};
Alternative implementation:
let t = s.strip_prefix(p).u
nwrap_or(s);
Removes p at most once.
Go
Rust
Python
Kotlin
Scala
Dart
168 Trim suffix import "strings" let t = s.trim_end_matches t = s.removesuffix(w)
Create string t consisting of string s with its suffix (w);
t := strings.TrimSuffix(s, w) removesuffix is in Python 3.9+
w removed (if s ends with w).
This may remove several
occurrences of w at the end of s.
Alternative implementation:
let t = s.strip_suffix(w).u
nwrap_or(s);
Removes at most 1 occurrence
of w
169 String length import "unicode/utf8" let n = s.chars().count(); n = len(s) val n = s.length val n = s.length() int n = s.length;
Assign to integer n the number of characters of
n := utf8.RuneCountInString(s) This is kind of roundabout If s is a Python 3 str, len(s)
string s.
import "strconv"
n := strconv.Itoa(23489)
s := thousands.Separate(n, "en")
use error_chain::error_chai
Alternative implementation: resp = request.urlopen(re
n;
import "net/http"
q)
use std::io::Read;
import "net/url" Explicit use of the "method"
let client = reqwest::block parameter, because "GET" is
response, err := http.PostForm(u, formValue ing::Client::new();
used when "data" is None
s) let mut response = client.p
formValues has type net/url.Values ost(u).body("abc").send()?;
This is a synchronous
(blocking) reqwest call.
for byte in a {
176 Hex string to byte array import "encoding/hex" use hex::FromHex; a = bytearray.fromhex(s)
From hex string s of 2n digits, build the
equivalent array a of n bytes.
a, err := hex.DecodeString(s)
let a: Vec<u8> = Vec::from_
Each pair of hexadecimal characters (16 possible if err != nil {
hex(s).expect("Invalid Hex
values per digit) is decoded into one byte (256 log.Fatal(err)
String");
possible values). }
if err != nil {
L = [f for f in os.listdi
fmt.Printf("failure accessi r(D) if os.path.splitext
ng a path %q: %v\n", path, err)
(f)[1] in extensions]
return err
import re
L = append(L, path)
import os
break
}
filtered_files = ["{}/
}
{}".format(dirpath, filen
return nil
ame) for dirpath, _, file
}) names in os.walk(D) for f
ilename in filenames if r
e.match(r'^.*\.(?:jpg|jpe
g|png)$', filename)]
* list comprehension
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
L = [f for f in glob.glob
(os.path.join(D, "**/*"),
recursive=True)) if os.pa
th.splitext(f)[1] in exte
nsions]
Go
Rust
Python
Kotlin
Scala
Dart
178 Check if point is inside rectangle import "image" struct Rect {
b = (x1 < x < x2) and (y1
Set boolean b to true if if the point with x1: i32,
< y < y2)
coordinates (x,y) is inside the rectangle with p := image.Pt(x, y)
x2: i32,
Edges NOT considered to be
coordinates (x1,y1,x2,y2) , or to false otherwise.
r := image.Rect(x1, y1, x2, y2)
y1: i32,
inside.
Describe if the edges are considered to be inside b := p.In(r) y2: i32,
as in the rectangle.
impl Rect {
fn contains(&self, x: i
32, y: i32) -> bool {
Alternative implementation:
let x = std::fs::read_dir
(d)?.collect::<Result<Vec<_
>, _>()?;
Go
Rust
Python
Kotlin
Scala
Dart
182 Quine program package main
fn main() {
s = 's = %r\nprint(s%%s)'
object Quine extends
Output the source of the program. let x = "fn main() {\n print(s%s) App {
import "fmt"
let x = ";
val s =
s, 0x60)
print!("{}{:?};
| ""%2$s%1
}
let y = {:?};
$s%2$s""
{}", x, x, y, y)
| print(s.stri
var s = `package main
} pMargin.format(s,
"\""))
import "fmt"
Alternative implementation: |}"""
fn main(){print!("{}, print(s.stripMargi
func main() {
{0:?})}}","fn main(){print! n.format(s, "\""))
var s = `
return err
headers = {'Content-Typ
}
e': content_type}
req.Header.Set("Content-Type", contentType)
data = {}
req.ContentLength = contentLength
beforehand.
status_code, content = r.
body is a io.Reader which can be nil. status_code, r.content
184 Tomorrow import "time" let t = chrono::Utc::now(). from datetime import dat var now = new Date
Assign to variable t a string representing the day, date().succ().to_string(); e, timedelta Time.now();
month and year of the day after the current date. t := time.Now().Add(24 * time.Hour).Format var t = now.add(ne
("2006-01-02") t = str(date.today() + ti
w Duration(days:
medelta(days=1))
1));
Go
Rust
Python
Kotlin
Scala
Dart
185 Execute function in 30 seconds import "time" use std::time::Duration;
import threading
Schedule the execution of f(42) in 30 seconds. use std::thread::sleep;
timer := time.AfterFunc(
timer = threading.Timer(3
30*time.Second,
sleep(Duration::new(30, 0.0, f, args=(42,) )
func() {
0));
timer.start()
f(42)
f(42);
})
f is wrapped in an anonymous func having 0 arg
and 0 return value.
Alternative implementation:
import "time"
go func() {
time.Sleep(30 * time.Second)
f(42)
}()
The code after the goroutine launch executes
immediately.
self.rank = [0] *
size
self.p = [i for i
in range(size)]
def find_set(self,
i):
if self.p[i] ==
i:
return i
else:
self.p[i] = s
elf.find_set(self.p[i])
return self.p
[i]
def is_same_set(self,
i, j):
return self.find_
set(i) == self.find_set
(j)
def union_set(self,
i, j):
if not self.is_sa
me_set(i, j):
x, y = self.f
ind_set(i), self.find_set
(j)
with ny rows and nz columns and assign the c.Mul(a, b) Python 3.5 (PEP465)
value to a real matrix c with nx rows and nz introduced the @ operator for
columns. matrix multiplication.
Alternative implementation:
import numpy as np
c = np.matmul(a, b)
You can also use np.matrix
instead of np.array. Be careful
when using array, because the
* operator performs
elementwise multiplication.
Go
Rust
Python
Kotlin
Scala
Dart
189 Filter and transform list var y []Result
let y = x.iter()
y = [T(e) for e in x if P val y = x.collect { c
Produce a new list y containing the result of for _, e := range x {
.filter(P)
(e)] ase e if P(e) => T(e)
function T applied to all elements e of list x that if P(e) {
.map(T)
}
match the predicate P. y = append(y, T(e))
.collect::<Vec<_>> Alternative implementation:
}
(); y = list(map(T, filter(P,
} x)))
No functional style: just a regular loop.
9};
///
and call it, passing an array (or a list) of size 10 C.foo(C.a, 10) fn foo(a: *mut libc::c_
to a and 10 to n.
double, n: libc::c_int);
let n = 10;
unsafe {
foo(a.as_mut_ptr(), n);
limit if v > x {
m > x) {
f()
Given a one-dimensional array a, check if any f()
f()
192 Declare a real variable with at least 20 digits import "math/big" use rust_decimal::Decimal;
import decimal
Declare a real variable a with at least 20 digits; if use std::str::FromStr;
the type does not exist, issue an error at compile a, _, err := big.ParseFloat("123456789.1234 a = decimal.Decimal('1234
time. 56789123465789", 10, 200, big.ToZero) let a = Decimal::from_str 567890.123456789012345')
2nd arg is the base.
("1234567890.12345678901234
3rd arg is the precision.
5").unwrap();
4th arg is the rounding mode.
interchange). b = a.T
Alternative implementation:
a = [[1,2], [3,4], [5,6]]
b = list(map(list, zip(*
a)))
and the sum of all its elements when each fn foo(a: Vec<Vec<usize>>)
x*(i+1) + y*(i+1)
element is multiplied with the array indices i and j {
rate(a)
"Length of array:
))
{}",
a.clone()
.into_iter()
.flatten()
.collect::<Vec<
usize>>()
.len()
);
sum += i * j
println!("Sum of all pr
oducts of indices: {}", su
m);
}
By useing izip! macro we can
chain itteration over elements of
array a
196 Pass a sub-array fn foo(el: &mut i32) {
def foo(data, r):
fun foo(a : IntAr
Given an integer array a of size n, pass the first, *el = 42;
for i in r: data[i] = ray, idx: IntProg
third, fifth and seventh, ... up to the m th element }
42
ression) =
Go
Rust
Python
Kotlin
Scala
Dart
197 Get a list of lines from a file import "io/ioutil"
use std::io::prelude::*;
with open(path) as f:
import java.io.Fi
Retrieve the contents of file at path into a list of import "strings" use std::io::BufReader;
lines = f.readlines() le
strings lines, in which each element is a line of use std::fs::File;
the file. func readLines(path string) ([]string, erro val lines = File
r) {
let lines = BufReader::new (path).readLines
b, err := ioutil.ReadFile(path)
(File::open(path).unwrap())
()
if err != nil {
.lines()
198 Abort program execution with error condition import "os" use std::process; import sys
Abort program execution with error condition x
(where x is an integer value) os.Exit(x) process::exit(x); sys.exit(x)
This does not run any
destructors. Clean up is left to
the OS.
199 Truncate a file at the current file position import "os" F.truncate(F.tell())
Truncate a file F at the given file position.
err := os.Truncate(F, position)
num.powf(0.5)
202 Sum of squares import "math" let s = data.iter().map(|x| s = sum(i**2 for i in dat
Calculate the sum of squares s of data, an array x.powi(2)).sum::<f32>(); a)
of floating point values. var s float64
s += math.Pow(d, 2)
203 Calculate mean and standard deviation import "github.com/gonum/stat" import statistics
Calculate the mean m and the standard deviation
s of the list of floating point values data. m, s := stat.MeanStdDev(data, nil) m = statistics.mean(data)
204 Return fraction and exponent of a real import "math" import math
number
Given a real number a, print the fractional part fmt.Println(math.Frexp(a)) print(math.frexp(a))
and the exponent of the internal representation of
that number. For 3.14, this should print
(approximately)
0.785 2
Go
Rust
Python
Kotlin
Scala
Dart
205 Get an environment variable import "os" use std::env; import os
Read an environment variable with the name
"FOO" and assign it to the string variable foo. If it foo, ok := os.LookupEnv("FOO")
let foo;
try:
e".to_string(),
foo = "none"
Alternative implementation: }
import "os" Alternative implementation:
Alternative implementation: from os import getenv
foo := os.Getenv("FOO")
use std::env;
if foo == "" {
foo = getenv('FOO', 'non
foo = "none"
let foo = env::var("FOO").u e')
} nwrap_or("none".to_string
This is fine if empty string means "no value" in your ()); Alternative implementation:
use case.
import os
Alternative implementation:
foo = os.environ.get('FO
To distinguish between an empty value and an use std::env;
O', 'none')
unset value, use os.LookupEnv.
let foo = match env::var("F Python exposes environment
OO") {
variables as an associative
Ok(val) => val,
array(dict), so the standard get
Err(_e) => "none".to_st method can be used.
ring(),
};
Alternative implementation:
use std::env;
//
}
Go
Rust
Python
Kotlin
Scala
Dart
206 Switch statement with strings switch str {
match str {
switch = {'foo': foo,
case "baz":
_ => {}
baz()
}
switch_funct = switch.get
case "barfl":
(string)
barfl()
if switch_funct : switch_
} funct()
Python does not natively
support switch statements, but
we can use a dictionary to
replicate one.
deallocated a = [0] * n
reference.
+ math.Cos(d[i]))
of the variables should be f32 or
}
f64 in order to use the cos() Alternative implementation:
} method.
import math
a = [e*(a[i] + b[i] + c
[i] + math.cos(d[i])) for
i in range(len(a))]
Go
Rust
Python
Kotlin
Scala
Dart
209 Type with automatic deep deallocation type t struct {
struct T {
class T:
After v goes out of scope, v and all its fields will be n: vec![1, del v
};
}
When a variable goes out of
scope, all member variables are
deallocated recursively.
210 Compiler version and options import "runtime" import sys
Assign, at runtime, the compiler version and the
options the program was compilerd with to version := runtime.Version() version = sys.version
Example output:
-mtune=generic -march=x86-64
{
'ᾺΙ ΣΤΟ ΔΙΆΟΛ
println!("{:?} == Ο']
} for a, b in itertools.com
binations(strings, 2):
print(a, b, a.casefol
d() == b.casefold())
}
c here is a one-character string
Go
Rust
Python
Kotlin
Scala
Dart
215 Pad string on the left import "strings"
use unicode_width::{Unicode s = s.rjust(m, c)
Prepend extra character c at the beginning of import "utf8" WidthChar, UnicodeWidthSt
string s to make sure its length is at least m.
r};
The length is the number of characters, not the if n := utf8.RuneCountInString(s); n < m {
let padding_width = c
.width()
.filter(|n| *n > 0)
.expect("padding ch
aracter should be visibl
e");
let padding_needed = co
lumns_short + padding_width
- 1 / padding_width;
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.
h::new(_name);
TED) as zip:
import "io/ioutil"
let file = std::fs::File::c for file in list_:
buf := new(bytes.Buffer)
reate(&path).unwrap();
zip.write(file)
w := zip.NewWriter(buf)
let mut zip = zip::ZipWrite Files listed in list_
for _, filename := range list {
r::new(file); zip.start_fil
input, err := os.Open(filename)
e("readme.txt", FileOption
if err != nil {
s::default())?;
return err
zip.write_all(b"Hello, Worl
}
d!\n")?;
}
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();
if err != nil {
for i in _list.iter() {
return err
zip.start_file(i as
} &str, FileOptions::default
())?;
filesystem.
zip.finish()?;
lect::<HashSet<_>>();
This avoids converting b into a
setb[y] = true
let c = unique_a.intersecti
on(&unique_b).collect::<Vec
var c []T
<_>>();
for x := range seta {
if setb[x] {
Alternative implementation:
c = append(c, x)
use std::collections::HashS
}
et;
}
Convert to sets, then iterate in one pass.
let set_a: HashSet<_> = a.i
The runtime cost is O(n).
nto_iter().collect();
let c = set_a.intersection
(&set_b);
219 Replace multiple spaces with single space import "regexp" use regex::Regex; import re
Create string t from the value of string s with
each sequence of spaces replaced by a single whitespaces := regexp.MustCompile(`\s+`)
let re = Regex::new(r"\s t = re.sub(' +', ' ', s)
space.
t := whitespaces.ReplaceAllString(s, " ") +").unwrap();
Only replaces spaces.
The whitespaces regexp can be reused. let t = re.replace_all(s, "
Explain if only the space characters will be ");
replaced, or the other whitespaces as well: tabs, Replaces all whitespaces.
newlines.
220 Create a tuple value t := []interface{}{
let t = (2.5, "hello", -1); t = (2.5, "hello", -1)
Create t consisting of 3 values having different 2.5,
Tuples are like “fixed-length Tuples are immutable.
types.
"hello",
collections of values of different They may be created with
make(chan int),
types”. elements of any type.
Explain if the elements of t are strongly typed or } They are strongly typed.
not.
A slice of empty interface may hold any values (not
strongly typed).
Alternative implementation:
a, b, c := 2.5, "hello", make(chan int)
a, b, c are strongly typed and could hold the
multiple return values of a func.
contain x. i = j
break
let i = match opt_i {
}
Some(index) => index as
} i32,
Alternative implementation:
let i = items.iter().positi
on(|y| *y == x).map_or(-1,
|n| n as i32);
Rust uses the usize type to
index lists, but it can't be
negative. We need to manually
convert it to an i32 to be able to
return -1
Go
Rust
Python
Kotlin
Scala
Dart
223 for else loop items := []string{"foo", "bar", "baz", "qu let mut found = false;
items = ['foo', 'bar', 'b items.find { it -
Loop through list items checking a condition. Do x"}
for item in items {
az', 'qux']
> it == "baz" }?.
something else if no matches are found.
if item == &"baz" {
let {
}
}
print('never found i Alternative
These are mostly used as an inner nested loop, {
if !found {
t') implementation:
and in a location where refactoring inner logic fmt.Println("never found it")
println!("never found i if(items.any { it
into a separate function reduces clarity. }
t");
Alternative implementation: == "baz" })
star programmer") {
The "in" operator is more
println!("NotFoun idiomatic than looping over a
d");
container. However the run-
}; time performance is tied to the
type of collection being iterated
Alternative implementation: over.
items
.iter()
.find(|&&item| item ==
"rockstar programmer")
.or_else(|| {
println!("NotFoun
d");
Some(&"rockstar pro
grammer")
});
find returns the first Some(T)
that satisfies condition, or
returns None. We can use
or_else to do action when None
is returned. If you'd like to do
something with found element,
use and_then.
Go
Rust
Python
Kotlin
Scala
Dart
224 Add element to the beginning of the list items = append([]T{x}, items...) use std::collections::VecDe items = [x] + items
Insert element x at the beginning of list items. que;
items has type []T.
Alternative implementation:
items = append(items, x)
copy(items[1:], items)
items[0] = x
This implementation is verbose, but it will often not
allocate, when items has enough capacity.
225 Declare and use an optional argument func f(x ...int) {
fn f(x: Option<()>) {
def f(x=None):
println("Not present")
None => println!("N else:
}
ot present"),
print("Present",
} }
x)
Go does not have optional arguments, but to some }
extend, they can be mimicked with a variadic
parameter.
if err != nil {
return err
if err != nil {
return err
Alternative implementation:
import "io/ioutil"
import "os"
if err != nil {
return err
if err != nil {
return err
if err != nil {
return err
}
This is fine if the file is small enough to fit in
memory.
Alternative implementation:
import "io"
import "os"
Go
Rust
Python
Kotlin
Scala
Dart
func copy(dst, src string) error {
f, err := os.Open(src)
if err != nil {
return err
defer f.Close()
if err != nil {
return err
if err != nil {
return err
defer g.Close()
_, err = io.Copy(g, f)
if err != nil {
return err
}
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.
defer cancel()
p(ctx)
p is responsible for shutting down gracefully when
ctx is canceled.
231 Test if bytes are a valid UTF-8 string import "unicode/utf8" let b = std::str::from_utf8 try:
b = False
Go
Rust
Python
Kotlin
Scala
Dart
232 Read a command line boolean flag import "flag" use clap::{Arg, App}; import argparse
Print "verbose is true" if the flag -v was passed to
the program command line, "verbose is false" var verbose = flag.Bool("v", false, "verbos let matches = App::new("My parser = argparse.Argumen
otherwise. e")
Program")
tParser()
flag.Parse()
.arg(Arg::w parser.add_argument('-v',
fmt.Println("verbose is", *verbose) ith_name("verbose")
action='store_true', dest
verbose has pointer type *bool.
.short ='verbose')
Call Parse only once, after all flags are defined and ("v")
args = parser.parse_args
before flags are read.
.takes_ ()
s();
if matches.is_present("verb
ose") {
println!("verbose is tr
ue")
} else {
println!("verbose is f
alse")
233 Read a command line string flag import "flag" import argparse
Print the value of the flag -country passed to the
program command line, or the default value var country = flag.String("country", "Canad parser = argparse.Argumen
"Canada" if no such flag was passed. a", "user home country")
tParser()
flag.Parse()
parser.add_argument('-cou
fmt.Println("country is", *country) ntry', default='Canada',
country has pointer type *string.
dest='country')
Call Parse only once, after all flags are defined and args = parser.parse_args
before flags are read.
()
234 Encode bytes to base64 import "encoding/base64" let s = base64::encode(dat import base64
Assign to string s the standard base64 encoding a);
of the byte array data, as specified by RFC 4648. s := base64.StdEncoding.EncodeToString(dat b = base64.b64encode(dat
a) a)
s = b.decode()
b is a bytes object
s is a unicode string
Go
Rust
Python
Kotlin
Scala
Dart
235 Decode base64 import "encoding/base64" let bytes = base64::decode import base64 import java.util.
Assign to byte array data the bytes represented (s).unwrap();
Base64
by the base64 string s, as specified by RFC data, err := base64.StdEncoding.DecodeStrin data = base64.decode(s)
4648. g(s) String(Base64.get
Decoder().decode
(s))
Unfortunately, at the
time of the writing, I
couldn't find kotlin's
decoder that uses
base64 however
ASCII and UTF
decoders are
natively available
236 Large quotient import "math/big" import fractions
Initialize a quotient q = a/b of arbitrary precision.
a and b are large integers. q := new(big.Rat)
q = fractions.Fraction(a,
q.SetString(str) b)
str is a quotient string including numerator, slash,
denominator.
Alternative implementation:
import "math/big"
q := new(big.Rat)
q.SetFrac(a, b)
a, b have type *big.Int
Alternative implementation:
import "math/big"
q := big.NewRat(a, b)
This creates a quotient from int64 values.
Alternative implementation:
import "math/big"
c := new(big.Int)
c.Xor(a, b)
a, b, c have big integer type *big.Int
Go
Rust
Python
Kotlin
Scala
Dart
238 Xor byte arrays c := make([]byte, len(a))
let c: Vec<_> = a.iter().zi c = bytes([aa ^ bb for a
Write in a new byte array c the xor result of byte for i := range a {
p(b).map(|(x, y)| x ^ y).co a, bb in zip(a, b)])
arrays a and b.
c[i] = a[i] ^ b[i]
llect();
}
a and b have the same size.
Byte slices []byte are more idiomatic than arrays.
Alternative implementation:
var c T
for i := range a {
}
T is a fixed-sized array type, e.g. [5]byte.
239 Find first regular expression match import "regexp" use regex::Regex; import re
Assign to string x the first word of string s
consisting of exactly 3 digits, or the empty string re := regexp.MustCompile(`\b\d\d\d\b`)
let re = Regex::new(r"\b\d m = re.search(r'\b\d\d\d
if no such match exists.
x := re.FindString(s) \d\d\b").expect("failed to \b', s)
240 Sort 2 lists together import "sort" let mut tmp: Vec<_> = a.ite import operator
Lists a and b have the same length. Apply the r().zip(b).collect();
t []T
emgetter(0))
return len(s.k)
sort.Sort(&sorter{
k: a,
t: b,
})
The custom type sorter implements the 3 methods
of sort.Interface.
Swap affects the order of 2 slices at once.
Go
Rust
Python
Kotlin
Scala
Dart
241 Yield priority to other threads import "runtime" ::std::thread::yield_now();
Alternative implementation:
import "fmt"
fmt.Printf("%q", m)
The verb %q prints strings with nice double-quotes.
It's not the best for all types of keys and values,
though.
245 Print value of custom type import fmt; println!("{:?}", x); print(x)
Print the value of object x having custom type T,
fmt.Println(x) Implement fmt::Debug or
for log or debug.
fmt::Display for T
Will be more relevant if T implements fmt.Stringer
246 Count distinct elements distinct := make(map[T]bool)
use itertools::Itertools; c = len(set(items)) val c = items.dis
Set c to the number of distinct elements in list for _, v := range items {
tinct().size
items. let c = items.iter().unique
distinct[v] = true
().count();
}
c := len(distinct)
This assumes the type T is comparable with ==
Go
Rust
Python
Kotlin
Scala
Dart
247 Filter list in-place j := 0
let mut j = 0;
del_count = 0
Remove all the elements from list x that don't for i, v := range x {
for i in 0..x.len() {
for i in range(len(x)):
if p(v) {
x[j] = x[i]
j++
x[k] = nil
x = x[:j]
When elements of x have pointer type, it is
necessary to set discarded slice elements to nil, to
avoid a memory leak.
248 Construct a 64-bit floating-point value import math
Construct the "double precision" (64-bit) floating
point number d from the mantissa m, the sign = -1 if s else 1
for _, x := range m {
if i == k {
return x
i++
panic("unreachable")
Alternative implementation:
import "math/rand"
k := rand.Intn(len(m))
for _, x := range m {
if k == 0 {
return x
k--
panic("unreachable")
251 Parse binary digits import "strconv" let i = i32::from_str_radix i = int(s, 2) var i = int.parse
Extract integer value i from its binary string (s, 2).expect("Not a binary (s, radix: 2);
}
No syntactic sugar
253 Print stack trace import "runtime/debug" use backtrace::Backtrace; import inspect
Print the stack frames of the current execution
thread of the program. debug.PrintStack() let bt = Backtrace::new();
for frame in inspect.stac
Prints to standard error println!("{:?}", bt); k():
print(frame)
Go
Rust
Python
Kotlin
Scala
Dart
254 Replace value in list for i, s := range x {
for v in &mut x {
for i, v in enumerate(x):
Alternative implementation:
x = ["bar" if v=="foo" el
se v for v in x]
List comprehension
255 Print a set use std::collections::HashS print(x)
Print the values of the set x to the standard et;
output.
Use _(0..=5).rev()_.
print(i) print(i);
fmt.Println(i)
257 Traverse list backwards import "fmt" for (i, item) in items.iter for i in range(len(items)
Print each index i and value x from the list items, ().enumerate().rev() {
-1, -1, -1):
from the last down to the first. for i := len(items) - 1; i >= 0; i-- {
*item);
fmt.Printf("Item %d = %v \n", i, x)
}
}
258 Convert list of strings to list of integers import "strconv" let b: Vec<i64> = a.iter(). b = [int(elem) for elem i
Convert the string values from list a into a list of map(|x| x.parse::<i64>().un n a]
integers b. b := make([]int, len(a))
wrap()).collect();
var err error
for i, s := range a {
a has type Vec<&str>
b[i], err = strconv.Atoi(s)
Alternative implementation:
if err != nil {
return err
let b: Vec<i32> = a.iter().
}
flat_map(|s| s.parse().ok
} ()).collect();
ok converts a Result to an
Option. flat_map collects all
values of Some.
259 Split on several separators import "regexp" let parts: Vec<_> = s.split import re
Build list parts consisting of substrings of input (&[',', '-', '_'][..]).coll
string s, separated by any of the characters ',' re := regexp.MustCompile("[,\\-_]")
parts = re.split('[,_
ect();
(comma), '-' (dash), '_' (underscore). parts := re.Split(s, -1) \-]', s)
Square brackets mean "match any of these
characters".
261 Format time hours-minutes-seconds import "time" use time::macros::format_de import datetime
Assign to string x the value of fields (hours, scription;
minutes, seconds) of date d, in format x := d.Format("15:04:05") d = datetime.datetime.now
HH:MM:SS. let format = format_descrip ()
tion!("[hour]:[minute]:[sec x = d.strftime('%H:%M:%
ond]");
S')
let x = d.format(&format).e
xpect("Failed to format the
time");
262 Count trailing zero bits import "math/bits" let t = n.trailing_zeros(); t = bin(n)[::-1].find
Assign to t the number of trailing 0 bits in the ('1')
binary representation of the integer n.
t := bits.TrailingZeros(n)
Works for n > 0. Integers in
n has type uint
Python have no fixed bitsize,
E.g. for n=112, n is 1110000 is base 2 and the
so t is undefined for n = 0.
result is t=4
263 Integer logarithm in base 2 fn log2d(n: f64) -> f64 {
import math
Write two functions log2d and log2u, which n.log2().floor()
def log2u(n):
return math.ceil(mat
h.log2(n))
fn main() {
for n in 1..=12 {
let f = f64::from
print(n, log2d(n), lo
(n);
g2u(n))
println!("{} {}
{}", n, log2d(f), log2u Functions accept both int and
(f));
float parameters
}
}
Alternatively, you could use n as
f64 instead of f64::from(n), but
that doesn't pass the Clippy
pedantic lint cast_lossless.
Go
Rust
Python
Kotlin
Scala
Dart
264 Automated passing of array bounds fn foo(v: Vec<Vec<i32>>) {
def foo(a):
vec![1, 2, 3],
a = [[1,2,3], [4,5,6]]
vec![4, 5, 6],
foo(a)
];
foo(v);
Alternative implementation:
fn foo<const X: usize, cons
t Y: usize>(_: [[i32;X];Y])
{
println!("{} {}", Y,
X);
let a = [
[1, 2, 3],
[4, 5, 6],
];
foo(a);
Set the integer variable i to 42 and calculate its let p = i.count_ones() % 2; p = bin(i).count('1') % 2
parity (i.e. 0 if it contains an even number of bits,
1 if it contains an odd number of bits).
266 Repeated string import (
let s = v.repeat(n); s = v * n val s = v.repeat var s = v * n;
Assign to the string s the value of the string v "fmt"
(n)
String * num repeats
repeated n times, and write it out.
"strings"
println(s) copies of the string.
)
E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
s := strings.Repeat(v, n)
fmt.Println(s)
Go
Rust
Python
Kotlin
Scala
Dart
267 Pass string to argument that can be of any import "fmt" use std::any::Any; def foo(x):
type if isinstance(x, st
Declare an argument x to a procedure foo that func foo(x interface{}) {
fn foo(x: &dyn Any) {
r):
else:
} else {
println!("{}", s);
print('Nothing.')
return
procedure. }
println!("Nothing")
}
}
foo('Hello, world!')
foo(42)
func main() {
foo("Hello, world!")
fn main() {
foo(42)
foo(&"Hello, world!".to
} _owned());
self.z = z
return
return Vector(sel
f.y * other.z - self.z *
other.y,
sel
f.z * other.x - self.x *
other.z,
sel
f.x * other.y - self.y *
other.x)
result = a * b
Python doesn't allow operators
with user-defined names
269 Enum to String let e = t::bike;
e = T.horse
val e = T.BIKE
elif issubclass(type
(x), foo):
print("Extends ty
pe.")
else:
print("Not relate
d.")
elif i % 5 == 0:
defer dir.Close()
_, err = dir.Readdirnames(1)
b := err == io.EOF
Error may happen, and should be dealt with.
if unicode.IsSpace(r) {
return -1
return r
}, s)
In this mapping, -1 means "drop this character"
275 Binary digits to byte array import "strconv" n = (len(s) - 1) // 8 + 1
for i in range(n):
of n bytes.
a := make([]byte, n)
b = int(s[i * 8:(i +
Each chunk of 8 binary digits (2 possible values for i := range a {
1) * 8], 2)
per digit) is decoded into one byte (256 possible b, err := strconv.ParseInt(s[i*8:i*
a[i] = b
values). 8+8], 2, 0)
if err != nil {
log.Fatal(err)
a[i] = byte(b)
}
bytes are unsigned in Go (byte is an alias for
uint8)
Alternative implementation:
x[e] = true
x has type map[E]bool
Go
Rust
Python
Kotlin
Scala
Dart
277 Remove an element from a set delete(x, e) x.remove(e)
Remove the element e from the set x.
Alternative implementation:
delete(x, e)
x has type map[E]bool
line := s.Text()
This handles any error (including EOF) by aborting
the program execution.
log.Fatal(err)
}
WARNING: this works only for lines smaller than
64kB each.
280 Filter map for k, v := range x {
m = {k:v for k, v in m.it
Remove all the elements from the map m that if !p(v) {
ems() if p(v)}
don't satisfy the predicate p.
delete(x, k)
Creates a new map.
Keep all the elements that do satisfy p.
}
} Alternative implementation:
Explain if the filtering happens in-place, i.e. if m
It is safe to use delete while iterating.
for k in list(m):
y. Create a map m with key type Point (or m[p] = "Hello" m[p] = 'Hello'
equivalent) and value type string. Insert "Hello" at
Types comparable with == can be used as map Dictionary keys must be
position (42, 5).
keys. hashable objects. User-defined
classes are hashable by
default.
Alternative implementation:
from collections import n
amedtuple
Point = namedtuple('Poin
t', 'x y')
p = Point(42, 5)
m = {p: "Hello"}
m = {Point(42, 5): "Hello"}
would work just fine, as well!
Naming the point in advance,
has the advantage of using
both p and Point(42, 5) as a
key
282 Use a custom type as map key type Foo struct {
Declare a type Foo, and create a new map with name string
Alternative implementation:
let parts = s.split(sep).co
llect::<Vec<&str>>();
s may have type &str or String.
Alternative implementation:
let parts: Vec<&str> = s.sp
lit(sep).collect();
s may have type &str or String.
284 Created a zeroed list of integers a := make([]int, n) let a = vec![0; n]; a = [0] * n
Create a new list a (or array, or slice) of size n,
All elements have the default value 0.
where all elements are integers initialized with
the value 0.
Go
Rust
Python
Kotlin
Scala
Dart
285 Set variable to NaN a = float('nan')
len counts bytes (not runes). The len method counts the Python strings are sequences
number of bytes, not the number of Unicode codepoints, the
This can be different from the number of
of characters. internal representation is
characters. If n includes more bytes than the
implementation dependent. But
characters per se (trailing zero, length field, etc.)
you can easily determine the
then explain it. One byte is 8 bits.
length of a specific byte
encoding.
288 Check if set contains a value b := x[e] let b = x.contains(&e); b = e in x
Set the boolean b to true if the set x contains the
x has type map[E]bool x has type HashSet
element e, false otherwise.
Alternative implementation:
_, b := x[e]
x has type map[E]struct{}
289 Concatenate two strings s := a + b let s = format!("{}{}", a, s = a + b val s = a + b
Create the string s by concatenating the strings a b);
and b.
This allocates a new String with
a and b concatenated.
Alternative implementation:
let s = a + b;
This adds b to the current
allocation of a, meaning that a
needs to be a mutable String.
Go
Rust
Python
Kotlin
Scala
Dart
290 Sort sublist sub := items[i:j]
items[i..j].sort_by(c); import functools
Sort the part of the list items from index i sort.Slice(sub, func(a, b int) bool {
Sorts a slice of items. items[i:j] = sorted(items
(included) to index j (excluded), in place, using return c(sub[a], sub[b])
the comparator c.
[i:j], key=functools.cmp_
})
to_key(c))
A slice can be sorted in place.
Elements before i and after j must remain c is an old-style comparison
unchanged. function
Alternative implementation:
items[i:j] = sorted(items
[i:j], key=c)
c is a key function, see the
doc.
291 Remove sublist copy(items[i:], items[j:])
items[i:j] = []
Delete all the elements from index i (included) to for k, n := len(items)-j+i, len(items); k <
index j (excluded) from the list items. n; k++ {
Alternative implementation:
items[k] = nil
del items[i:j]
}
items = items[:len(items)-j+i]
Use this when the elements of items have a
pointer type.
Alternative implementation:
items = append(items[:i], items[j:]...)
Use this when the elements don't have a pointer
type.
292 Write "Ni Hao" in Chinese to standard output import "fmt" print('Hello World and \u
in UTF-8 4f60\u597d')
Write "Hello World and 你好" to standard output fmt.Println("Hello World and 你好")
in UTF-8.
Strings are UTF-8 by default.
293 Create a stack let mut s: Vec<T> = vec![];
s = []
Given an array a, assign the values 1,12,42 to it, print(*a, sep=', ')
1, 12, 42