Python, Kotlin, Go, Rust, Dart, Ruby Cheat Sheet
Python, Kotlin, Go, Rust, Dart, Ruby Cheat Sheet
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')
}
iterator.
a new line 10 times
}
Alternative
implementation:
for(x in 1..10) {
println("Hel
lo")
{.
3.6
Alternative implementation:
import "fmt"
}
This is a closure.
Alternative
x: float
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|
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|
$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');
});
initial content.
critical, see docs x.insert("two", 2);
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;
("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)
Alternative implementation:
class Node:
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"
})
Alternative implementation:
import "math/rand"
j := rand.Intn(i + 1)
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();
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)
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);
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())
} traverse(bt.rig
method Dfs. }
parent.
Children is a slice of pointers.
of a tree f(root)
if t == nil {
children: Vec<Tree<V>>,
e, f(value)) {
f.(node)
}
self, f: F) {
}
} self.dfs_helper(& }
method Dfs .
}
(f)(&self.value);
child.dfs_helpe
r(f)
// ...
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)
matching cell.
tem.index(x) xed { i, row ->
return tru for (j, column) in Position search(Li end
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) {
return null;
a and b b = tmp;
Alternative implementation:
let (a, b) = (b, a);
Alternative implementation:
let i = match s.parse::<i32
>() {
Ok(i) => i,
};
l; puts queue.pop
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();
x := make([][]float64, m)
for i := range x {
x[i] = buf[:n:n]
buf = buf[n:]
return x
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 := make([][][]float64, m)
growable: false),
getter sort.Sort(sorter)
sort.Slice(items, less)
more idiomatic.
items[len(items)-1] = nil
tasks wg := sync.WaitGroup{}
let threads: Vec<_> = (0..1
end
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();
any value.
}
}
thread.join();
Alternative implementation:
extern crate rayon;
use rayon::prelude::*;
(0..1000).into_par_iter().f
or_each(f);
(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] }
i * f(i - 1)
match num {
0 | 1 => 1,
_ => factorial(num
- 1) * num,
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
}
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 = threading.Lock()
var lock sync.RWMutex
Dart is single- x = Atomic.new(0)
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();
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)
}
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)
parameter. (f(x)))
Alternative implementation:
fn compose<A, B, C>(f: impl
Fn(A) -> B, g: impl Fn(B) -
> C) -> impl Fn(A) -> C {
37 Currying from functools import par type PayFactory func(Company, *Employee, *E fn add(a: u32, b: u32) -> u adder = -> a, b { a + b }
print (f(2)(1))
#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
Alternative implementation:
use substring::Substring;
Neighbours map[*Vertex]bool
}
v = Vertex.new(1, 2, 3)
self.default_factory
The map is used as a Set of Vertex pointers.
graph = Graph.new(v, neighbour
= Vertex
self.make_path(pat
h)
self[l1].add(l2)
self[l2].add(l1)
G = Graph((0, 1, 2, 3),
(1, 4, 2))
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|
list b.
if v == u:
if v == w {
continue 'oute var b = [2, 3];
throw :matched if v == u
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;
exceptions. }
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]}");
akOuterLoop
}
except BreakOuterLoop:
}
pass }
Alternative implementation:
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))
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.
Alternative
implementation:
import "dart:asyn
c";
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
51 Check if map contains k in m import kotlin.col _, ok := m[k] use std::collections::HashM m.containsKey(k) m.include?(k)
}
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);
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.
1000.
p.map(func=f, ite s.Default).async wg.Done()
t.join();
any value.
print('Finished') }
wg.Wait()
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)
Python2
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);
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();
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.
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)
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(:*)
+ 1);
ne();
for i in 0..k {
return math.comb(n, }
res = (res * (n -
k) i).to_bigint().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
Alternative implementation:
x := make([]uint64, (n+63)/64)
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)
}
A Factory is a function which returns an object.
integers a and b. Use an The first two arguments can be ignored in this use use num::bigint::BigInt; var t = b;
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);
while (b != 0) {
b = 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.
import "math/big"
s := fmt.Sprintf("%b", x)
x has the type *big.Int.
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 .
i &= 0x0f0f0f0f0f0f0f0f
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.
about overflow.
}
checked_add is available for all
(x+y) overflows.
about overflow.
checked_mul is available on all
x, y and return true if return d/y != x
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> {
}
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
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
&self.x
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;
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;
return err
::serde_json::to_writer(&Fi f.puts(x.to_json)
}
le::create("data.json")?, & end
// 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
parameter } } end
Implement procedure def control(f):
type.
println!("{}", type_of(&
x));
}
Alternative implementation: "stat -f%z #{path}"
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()
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)
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.
Python
Kotlin
Go
Rust
Dart
Ruby
101 Load from HTTP GET import urllib.request
import "io/ioutil"
extern crate reqwest;
require 'net/http'
}
())?;
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.
p.Status)
s, file)?;
open('result.txt', 'w') do
}
},
|file|
return err
e),
file.write(chunk)
}
}; end
defer out.Close()
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"
contents into the object Use "pip install" to get this if err != nil {
x.
third-party library. It's industry return err
if err != nil {
return err
buffer is a []byte.
if err != nil {
return err
.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()))
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 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()?
.expect("the current ex
containing the currently absolutePath, err := filepath.Abs(programPa
e should exist")
running executable.
th)
.parent()
.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:
.expect("failed to exec
ute process");
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 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);
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.
x := mymap[k]
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) {
itemgetter(1)):
sort.Sort(entries)
}
Define custom types entry and entries.
Alternative implementation:
import "fmt"
import "sort"
key string
value int
})
}
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
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)
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{}{}
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)
preserved ().unique().collect();
}
x = x2
Original 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 = 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).
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"
}
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;
port p and read 1024 sock = socket.socket(sock let mut b = [0 as u8; 102 require 'socket'
"net"
"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)
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 {
CLUBS. Diamonds
} }
define :HEARTS, "hearts"
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)
/ 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
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
p (Time.now - t1)*1000000
in nanoseconds, of a call ()
foo()
let start = Instant::now();
t1 := time.Now()
foo()
t := time.Since(t1)
ns := t.Nanoseconds()
fmt.Printf("%dns\n", ns)
t1 has type time.Time.
fun useFoo() {
} end
val a, b = foo
()
n = Q.pop }
(0)
queue := []*Tree{root}
value: V
f(n)
for len(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...)
e::new();
}
q.push_back(self);
q.push_back
(child);
129 Breadth-first traversing from collections import d func (start *Vertex) Bfs(f func(*Vertex)) {
use std::rc::{Rc, Weak};
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)
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 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);
in a graph f):
map[*Vertex]bool) {
use std::cell::RefCell;
Call a function f on every seen = set()
seen[v] = true
stack = [start]
f(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 }
(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);
f1()
Using if and else } else if (c2) {
f1
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
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
yield
Time.now - t
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()
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 = [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
position i.
if y == x {
copy(items[i:], items[i+
1:])
items[len(items)-1] = nil
items = items[:len(items)-
1]
break
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
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]
Numeric_Type=Decimal, this
characters in range break
is not exactly the range '0'..'9'.
Alternative implementation:
let b = s.bytes().all(|c|
c.is_ascii_digit());
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);
import "math/big"
E.g. 999 -> "3e7"
s := fmt.Sprintf("%x", x)
x has type *big.Int.
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])
()), msg);
date and time.
ng.DEBUG, format="%(ascti prefix. logger.info(msg)
me)-15s %(message)s")
Writes an RFC3339 date to
Default Log format:
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"
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},
by default.
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
} else {
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"
p = strings.TrimSuffix(p, sep)
6,2)]
sign # .
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)
class RGB(numpy.ndarray):
b := (b1 + b2) / 2
@classmethod
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)
]).view(cls)
import "strconv"
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[:])
architecture char>() {
when 8 then f64
4 => f32(),
when 4 then f32
8 => f64(),
end
platform is 64-bit.
else:
}
_ => {}
}
compile-time condition f64()
if &arg == "f" {
fox();
ox()
func main() {
bat();
flag.Parse()
} else {
Alternative implementation: if *b {
eprintln!("invalid
options = {
bar()
'b': bat
}
'f': fox
if *f {
} else {
}
fox()
eprintln!("missing argu
}
ment");
()
match arg.as_str() {
_ => 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 {
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 import webbrowser import "github.com/skratchdot/open-golang/o use webbrowser; cmd = case RbConfig::CONFIG['h
default browser pen" ost_os']
en "start "
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.
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.
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.
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.
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"] }
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();
for byte in a {
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{}
import os if strings.HasSuffix(path,
ext) {
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]
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)
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)
false otherwise.
fn contains(&self, x: i end
and 1 for y.
}
Point.new((x1+x2)/2.0, (y1+
impl Rectangle {
end
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)
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)
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();
t = 1.day.since.to_s
Alternative implementation:
require "date"
t = Date.tomorrow.to_s
f(42)
timer.start()
func() {
0));
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)
}()
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)
limit f()
f()
a.each.with_index(1).sum do
size of the array, and the "Length of array:
)) |el, j|
el*i*j
end
end
end
puts foo(array)
.len()
);
sum += i * j
println!("Sum of all pr
oducts of indices: {}", su
m);
to 42.
foo(arry.select(&:odd?))
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 {
lengths x and y. }
203 Calculate mean and import statistics import "github.com/gonum/stat" m = data.sum / data.length.to_
standard deviation f
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") {
use std::env;
foo = getenv('FOO', 'non if foo == "" {
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") {
};
Alternative implementation:
use std::env;
//
}
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(),
funct() }
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());
}
(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)
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(),
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:
-mtune=generic -
march=x86-64
211 Create folder import os import "os" use std::fs; FileUtils.mkpath( 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
Ι ΣΤΟ ΔΙΆΟΛΟ']
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())
for a, b in itertools.com }
binations(strings, 2):
print(a, b, a.casefol
d() == b.casefold())
least m.
s += strings.Repeat(c, m-n)
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 {
.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;
sides
Add extra character c at
the beginning and
ending of string s to
make sure its length is at
least m.
import "io/ioutil"
for file in list_:
let file = std::fs::File::c
zip.write(file) buf := new(bytes.Buffer)
reate(&path).unwrap();
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()?;
c = list(set(a).intersect lect::<HashSet<_>>();
setb[y] = true
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;
}
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.
Alternative implementation:
let i = items.iter().positi
on(|y| *y == x).map_or(-1,
|n| n as i32);
print('found it')
} ?: println("nev fmt.Println("found it")
found = true;
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") {
.iter()
.find(|&&item| item ==
"rockstar programmer")
.or_else(|| {
println!("NotFoun
d");
Some(&"rockstar pro
grammer")
});
copy(items[1:], items)
items[0] = x
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.
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
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()
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()
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
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")
was passed. args = parser.parse_args Call Parse only once, after all flags are defined and
()
before flags are read.
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)
Alternative implementation:
import "math/big"
q := new(big.Rat)
q.SetFrac(a, b)
Alternative implementation:
import "math/big"
q := big.NewRat(a, b)
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 {
tmp.as_mut_slice().sort_by_
same permutation to a temp.sort(key=operator.it k []K
c<i32>) = tmp.into_iter().u
values of a. nzip();
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.
241 Yield priority to other import "runtime" ::std::thread::yield_now();
threads busywork();
Explicitly decrease the runtime.Gosched()
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 {
items. c := len(distinct)
list. nt]
}
}
that do satisfy p.
x = x[:j] x.truncate(j);
This is O(n^2)
Discarded elements are overwritten.
if p(v) {
x[j] = x[i]
j++
x[k] = nil
x = x[:j]
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.
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 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);
"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();
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}
string list x }
}
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--) {
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}" }
*item);
}
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("[,\\-_]")
characters ',' (comma), '-' The special character dash must be escaped with a
(dash), '_' (underscore). backslash.
261 Format time hours- import datetime import "time" use time::macros::format_de d = Time.now
262 Count trailing zero bits t = bin(n)[::-1].find import "math/bits" let t = n.trailing_zeros(); t = n.digits(2).index(1)
so t is undefined for n = 0.
}
(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() {
let f = f64::from
functions for numbers print(n, log2d(n), lo
(n);
}
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}"
println!("{} {}", Y,
X);
let a = [
[1, 2, 3],
[4, 5, 6],
];
foo(a);
s := strings.Repeat(v, n)
r):
"Nothing"
else:
print('Nothing.')
foo("Hello, world")
return
foo(42)
string, print it, otherwise }
println!("Nothing")
print "Nothing."
}
}
foo('Hello, world!')
foo(42)
procedure. foo(42)
foo(&"Hello, world!".to
} _owned());
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
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):
else:
print("Not relate
d.")
I/O.
print(i) elsif d5
puts "Buzz"
_, err = dir.Readdirnames(1)
b := err == io.EOF
Alternative implementation:
tabulations, etc. return -1
}
t = s.gsub(/\s/, "")
return r
}, s)
for i in range(n):
(2, "0")}
b = int(s[i * 8:(i +
digit characters ('0' or for i := range a {
1) * 8], 2)
array a of n bytes.
8+8], 2, 0)
values). }
EOF is reached. }
line := s.Text()
log.Fatal(err)
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.
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.
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);
del items[i:j]
the list items. }
items = items[:len(items)-j+i]
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.