In Python, there are 3 ways to read from stdin.
Using fileinput Module
This module implements a helper class and functions to quickly write a loop over standard input or a list of files. For example,
#!/usr/bin/python3
# Import module
import fileinput
for line in fileinput.input(encoding="utf-8"):
# process(input)
pass
abc
Note that this will include a newline character at the end. To remove the newline at the end, use line.rstrip().
Using sys.stdin
stdin is used for all interactive input.
See the following example:
#!/usr/bin/python3
# Import module
import sys
for line in sys.stdin:
# process(input)
pass
abc
Using input Function
The function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:
#!/usr/bin/python3
s = input('--> ')
print(s)
--> abc
abc
In Python, there are 2 ways to extract extension from filename.
Using os.path.splitext Method
The os.path.splitext(path) method splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period. For example,
#!/usr/bin/python3
# Import module
import os
name, ext = os.path.splitext("./file.txt")
print(name, ext)
# no extension
l = os.path.splitext("/a/b/c")
print(l)
./file .txt
('/a/b/c', '')
Leading periods of the last component of the path are considered to be part of the root:
#!/usr/bin/python3
# Import module
import os
l = os.path.splitext(".cshrc")
print(l)
l = os.path.splitext("/foo/....jpg")
print(l)
('.cshrc', '')
('/foo/....jpg', '')
Using pathlib.Path Method
A subclass of PurePath, this class represents concrete paths of the system’s path flavour.
#!/usr/bin/python3
# Import module
import pathlib
ext = pathlib.Path("./file.txt").suffix
print(ext)
ext = pathlib.Path(".cshrc").suffix
print(ext)
# all the suffixes
ext = pathlib.Path("./os.tar.gz").suffix
print(ext)
ext = pathlib.Path("./os.tar.gz").suffixes
print(''.join(ext))
.txt
.gz
.tar.gz
In Python, there are 3 ways to generate random integers between 0 and 9.
Using randrange Method
The random.randrange(start, stop[, step]) method returns a randomly selected element from range(start, stop, step). For example,
#!/usr/bin/python3
# Import module
import random
print(random.randrange(10))
print(random.randrange(7, 10))
4
8
Using randint Method
The random.randint(a, b) method returns a random integer N such that a
#!/usr/bin/python3
# Import module
import random
print(random.randint(7, 10))
# uniform gives you a floating-point value
print(random.uniform(7, 10))
8
7.8336193746821445
It is faster to use the random module than the secrets module.
Using randbelow Method
The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
To randomly print an integer in the inclusive range 0-9:
#!/usr/bin/python3
# Import module
import secrets
print(secrets.randbelow(10))
4
This is better than the random module for cryptography or security uses.
In Python, there are 3 ways to get the class name of an instance.
Using type Method
The type(object) method returns the type of an object. For example,
#!/usr/bin/python3
class A:
pass
a = A()
name = type(a).__name__
print(name)
A
Using Instance Classname
instance.__class__.__name__ represents the name of the class. For example,
#!/usr/bin/python3
class A:
pass
a = A()
print(a.__class__.__name__)
A
Using Qualified Name
You can simply use __qualname__ which stands for qualified name of a function or class:
#!/usr/bin/python3
class C:
class A:
pass
print(C.A.__qualname__)
C.A
In Python, there are 3 ways to pad a numeric string with zeros to the left.
Using zfill Method
The str.zfill(width) method returns a copy of the string left filled with ASCII '0' digits to make a string of length width. For example,
#!/usr/bin/python3
# s = str(n)
s = '6'
print(s.zfill(4))
# leading sign prefix
s = '-6'
print(s.zfill(4))
0006
-006
Using rjust Method
The str.rjust(width[, fillchar]) method returns the string right justified in a string of length width. For example,
#!/usr/bin/python3
s = '6'
print(s.rjust(4, '0'))
# leading sign prefix
s = '-6'
print(s.rjust(4, '0'))
0006
00-6
Using String Formatting and f-strings
You can use string formatting or f-strings to pad a numeric string with zeros to the left, it really simple. For example,
#!/usr/bin/python3
n = -6
print('%04d' % n)
print(format(n, '04'))
print('{0:04d}'.format(n))
print('{:04d}'.format(n))
# f-strings
# python >= 3.6
print(f'{n:04}')
print(f'{n:0>4}')
-006
-006
-006
-006
-006
00-6
In Python, there are 2 ways to delete an item from a dictionary.
Using del Statement
The easiest way to delete an item from a dictionary in Python:
#!/usr/bin/python3
m = {"a":1, "b":2}
# remove a
if 'a' in m:
del m['a']
print(m)
{'b': 2}
Using pop Method
If key is in the dictionary, remove it and return its value, else return default. For example,
#!/usr/bin/python3
m = {"a":1, "b":2}
# remove a
if 'a' in m:
# dict.pop(key[, default])
m.pop('a')
print(m)
{'b': 2}
And both of them will raise a KeyError if the key you're providing to them is not present in the dictionary.
Python Errors
Raise a KeyError:
del m['c']
del m['c']
KeyError: 'c'
In Python, there are 4 ways to remove a trailing newline.
Using rstrip Method
The str.rstrip() method returns a copy of the string with trailing characters removed. For example,
#!/usr/bin/python3
s = "\nab c\r\n"
# str.rstrip([chars])
n = s.rstrip()
# n = s.lstrip()
# n = s.strip()
print('{!r}'.format(n))
n = s.rstrip("\n")
print('{!r}'.format(n))
'\nab c'
'\nab c\r'
If omitted or None, the chars argument defaults to removing whitespace.
In addition to rstrip(), there are also the methods strip() and lstrip().
Using regex Module
You can use regex() module to remove a trailing newline, it really simple. For example,
#!/usr/bin/python3
# Import module
import re
s = "\nab c\r\n"
# trailing newline chars
n = re.sub(r'[\n\r]+$', '', s)
print('{!r}'.format(n))
# newline chars everywhere
n = re.sub(r'[\n\r]+', '', s)
print('{!r}'.format(n))
# only 1-2 trailing
n = re.sub(r'[\n\r]{1,2}', '', s)
print('{!r}'.format(n))
'\nab c'
'ab c'
'ab c'
Using translate Method
The str.translate() method returns a copy of the string in which each character has been mapped through the given translation table.
See the following example:
#!/usr/bin/python3
# Import module
import string
s = "\nab c\r\n"
n = s.translate({ord(c): None for c in string.whitespace})
print('{!r}'.format(n))
'abc'
Using splitlines Method
The str.splitlines() method returns a list of the lines in the string, breaking at line boundaries.
#!/usr/bin/python3
s = "\nab c\r\n"
n = ''.join(s.splitlines())
# n = ''.join(s.split())
print('{!r}'.format(n))
'ab c'
This method splits on the following line boundaries:
\nLine Feed\rCarriage Return\r\nCarriage Return + Line Feed\v or \x0bLine Tabulation\f or \x0cForm Feed\x1cFile Separator\x1dGroup Separator\x1eRecord Separator\x85Next Line (C1 Control Code)\u2028Line Separator\u2029Paragraph Separator
In Rust, there are 2 ways to convert Vec to a string.
Using collect Function
The collect() function transforms an iterator into a collection. collect() can take anything iterable, and turn it into a relevant collection. This is one of the more powerful methods in the standard library, used in a variety of contexts. For example,
fn main() {
let v = vec!["a", "b", "c"];
let s: String = v.into_iter().collect();
println!("{}", s);
}
abc
The original vector will be consumed. If you need to keep it, use v.iter().
Using from_iter Function
Creates a value from an iterator. See the following example:
fn main() {
let v = vec!["a", "b", "c"];
let s = String::from_iter(v);
println!("{}", s);
}
abc
In Rust, using the rev() function is the easiest way to make a reverse ordered for loop.
Using rev Function
The .rev() function reverses an iterator’s direction. Usually, iterators iterate from left to right. After using rev(), an iterator will instead iterate from right to left. For example,
fn main() {
for x in (0..5).rev() {
println!("{}", x);
}
}
4
3
2
1
0
This also works for most Iterators:
fn main() {
let v = vec!["a", "b", "c"];
for x in v.iter().rev() {
println!("{}", x);
}
}
c
b
a
In Rust, there are 3 ways to iterate over a string by character.
Using chars Method
The chars() method returns an iterator over the chars of a string slice. See the following example:
fn main() {
let s = "abc";
for c in s.chars() {
println!("{}", c);
}
// enumerate
for (i, c) in s.chars().enumerate() {
println!("{} {}", i, c);
}
}
a
b
c
0 a
1 b
2 c
Using Vec
You could also create a vector of chars and work on it from there, but that's more time and space intensive:
fn main() {
let s = "abc";
let v: Vec = s.chars().collect();
println!("{:?}", v);
}
['a', 'b', 'c']
It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want.
Using unicode-segmentation
Installation
This crate is fully compatible with Cargo. Just add it to your Cargo.toml:
[dependencies]
unicode-segmentation = "1"
unicode-segmentation Usage
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "a̐";
// chars
for c in s.chars() {
println!("{:?}", c);
}
// UnicodeSegmentation
for g in s.graphemes(true) {
println!("{:?}", g);
}
}
'a'
'\u{310}'
"a\u{310}"
Rust Compile Errors
no method named `graphemes` found for reference `&str` in the current scope
:
// use unicode_segmentation::UnicodeSegmentation;
for g in s.graphemes(true) {
error[E0599]: no method named `graphemes` found for reference `&str` in the current scope
--> src/main.rs:5:14
|
5 | for g in s.graphemes(true) {
| ^^^^^^^^^ method not found in `&str`
In Rust, there are 3 ways to update a value in a mutable HashMap.
Using get_mut Method
The get_mut() method returns a mutable reference to the value corresponding to the key. See the following example:
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
// Update a
*map.get_mut("a").unwrap() += 10;
println!("{}", map["a"]);
}
11
Using entry Method
You can use entry() to update a value in a mutable HashMap:
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
// Update a
*map.entry("a").or_insert(0) += 10;
println!("{}", map["a"]);
}
11
Using insert Method
You can use insert() to update a value of the key:
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("a", 1);
// Update a
map.insert("a", 10 + if map.contains_key("a") { map["a"] } else { 0 });
println!("{}", map["a"]);
}
11
Rust Compile Errors
cannot assign to data in an index of `HashMap`:
map["a"] += 10;
error[E0594]: cannot assign to data in an index of `HashMap`
--> src/main.rs:9:3
|
9 | map["a"] += 10;
| ^^^^^^^^^^^^^^ cannot assign
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap`
failed to resolve: use of undeclared type `HashMap`:
let mut map = HashMap::new();
error[E0433]: failed to resolve: use of undeclared type `HashMap`
--> src/main.rs:4:17
|
4 | let mut map = HashMap::new();
| ^^^^^^^ not found in this scope
|
help: consider importing this struct
|
3 | use std::collections::HashMap;
In Golang, there are 4 ways to generate a uuid.
Using uuid Package
install
Use the following command to download the repository to the local file system.
install
go mod tidy
go get github.com/google/uuid
go install github.com/google/uuid
Note that since Go 1.17 installing packages with go get is deprecated:
uuid Usage
The uuid package generates and inspects UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
See the following example:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
u := uuid.New()
fmt.Println(u.String())
}
69b03ce1-ad12-4c98-a66d-861cc240f382
Using uuidgen Command
If you are on linux or mac, you can alternatively call /usr/bin/uuidgen.
The uuidgen program creates (and prints) a new universally unique identifier (UUID) using the libuuid(3) library.
For example,
package main
import (
"fmt"
"os/exec"
)
func main() {
o, err := exec.Command("uuidgen").Output()
if err != nil {
// panic()
}
fmt.Printf("%s\n", o)
}
7b8cc5a3-f183-44b1-acb7-217eca047d43
Using uuid File
On Linux, you can read from /proc/sys/kernel/random/uuid:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, _ := ioutil.ReadFile("/proc/sys/kernel/random/uuid")
fmt.Println(string(b))
}
051c9f24-afac-4d53-8aa5-64602a6c89bb
Using crypto Package
crypto/rand pkg implements a cryptographically secure random number generator. This doesn't comply to any standard 2.
Note: NOT RFC4122 compliant.
package main
import (
"crypto/rand"
"fmt"
)
// Note - NOT RFC4122 compliant
func uuid() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
// panic()
return ""
}
return fmt.Sprintf("%04x-%04x-%04x-%04x-%04x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func main() {
s := uuid()
fmt.Println(s)
}
043ca19e-a8e7-b0f5-070f-8d7dbb240a19
In Golang, using the time.Unix() function is the easiest way to parse unix timestamp to time.Time
Using time.Unix Function
You can directly use time.Unix function of time which converts the unix time stamp to UTC.
See the following example:
package main
import (
"fmt"
"time"
)
func main() {
// sec seconds and nsec nanoseconds since January 1, 1970 UTC.
var i int64 = 1651383433
t := time.Unix(i, 0)
fmt.Println(t.UTC())
}
2022-05-01 05:37:13 +0000 UTC
Using milliseconds
The built-in time.Unix() function supports second and nanosecond precision. For example,
package main
import (
"fmt"
"time"
)
func main() {
var ms int64 = 1651383433905
t := time.Unix(ms/int64(1000), (ms%int64(1000))*int64(1000000))
fmt.Println(t.UTC())
}
2022-05-01 05:37:13.905 +0000 UTC
In Golang, there are 3 ways to trim leading and trailing white spaces of a string.
Using strings.TrimSpace Function
The easiest way to trim leading and trailing white spaces of a string in Golang. For example,
package main
import (
"fmt"
"strings"
)
func main() {
s := " \t \n Hello \r\n "
t := strings.TrimSpace(s)
fmt.Printf("%q\n", t)
}
"Hello"
Using strings.Trim Function
Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutset removed.
See the following example:
package main
import (
"fmt"
"strings"
)
func main() {
s := " \t \n Hello \r\n "
fmt.Printf("%q\n", strings.Trim(s, " \n\t"))
fmt.Printf("%q\n", strings.Trim(s, "\n "))
}
"Hello \r"
"\t \n Hello \r"
Using strings.TrimLeft or strings.TrimRight
To remove only the leading or the trailing characters, use strings.TrimLeft or strings.TrimRight. For example,
package main
import (
"fmt"
"strings"
)
func main() {
s := " \t \n Hello \r\n "
t := strings.TrimLeft(s, " \t\n")
t = strings.TrimRight(t, "\n ")
fmt.Printf("%q\n", t)
}
"Hello \r"
In Golang, there are 2 ways to get the maximum value for an int type.
Using constant values
Since integer types use two's complement arithmetic, you can infer the min/max constant values for int and uint. For example,
package main
import (
"fmt"
)
const MaxUint8 = ^uint8(0)
const MaxUint16 = ^uint16(0)
const MaxUint = ^uint(0)
const MinUint = 0
const MaxInt = int(MaxUint >> 1)
const MinInt = -MaxInt - 1
func main() {
fmt.Printf("uint8 %+v\n", MaxUint8)
fmt.Printf("uint16 %+v\n", MaxUint16)
fmt.Printf("uint64 %+v\n", MaxUint)
}
uint8 255
uint16 65535
uint64 18446744073709551615
The predeclared architecture-independent numeric types are:
uint8 (0 to 255)
uint16 (0 to 65535)
uint32 (0 to 4294967295)
uint64 (0
18446744073709551615)
int8 (-128 to 127)
int16 (-32768 to 32767)
int32 (-2147483648 to 2147483647)
int64 (-9223372036854775808
9223372036854775807)
Using math Package
We can use math package for getting the maximal and minimal values for integers:
package main
import (
"fmt"
"math"
)
func main() {
// integer max
fmt.Printf("i64 = %+v\n", math.MaxInt64)
fmt.Printf("i32 = %+v\n", math.MaxInt32)
fmt.Printf("i16 = %+v\n", math.MaxInt16)
// integer min
fmt.Printf("i64 = %+v\n", math.MinInt64)
fmt.Printf("i32 = %+v\n", math.MinInt32)
fmt.Printf("f64 = %+v\n", math.MaxFloat64)
fmt.Printf("f32 = %+v\n", math.MaxFloat32)
}
i64 = 9223372036854775807
i32 = 2147483647
i16 = 32767
i64 = -9223372036854775808
i32 = -2147483648
f64 = 1.7976931348623157e+308
f32 = 3.4028234663852886e+38
You can see more int the math package. The constants defined in the math package:
// Mathematical constants:
const (
// 3.40282346638528859811704183484516925440e+38
MaxFloat32 = 0x1p127 * (1 + (1 - 0x1p-23))
// 1.401298464324817070923729583289916131280e-45
SmallestNonzeroFloat32 = 0x1p-126 * 0x1p-23
// 1.79769313486231570814527423731704356798070e+308
MaxFloat64 = 0x1p1023 * (1 + (1 - 0x1p-52))
// 4.9406564584124654417656879286822137236505980e-324
SmallestNonzeroFloat64 = 0x1p-1022 * 0x1p-52
)
// Integer limit values:
const (
MaxInt = 1<<(intSize-1) - 1
MinInt = -1 << (intSize - 1)
MaxInt8 = 1<<7 - 1
MinInt8 = -1 << 7
MaxInt16 = 1<<15 - 1
MinInt16 = -1 << 15
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
MaxInt64 = 1<<63 - 1
MinInt64 = -1 << 63
MaxUint = 1<<intSize - 1
MaxUint8 = 1<<8 - 1
MaxUint16 = 1<<16 - 1
MaxUint32 = 1<<32 - 1
MaxUint64 = 1<<64 - 1
)
In Python, there are 3 ways to count the occurrences of a list item.
Using count Method
The str.count() method returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. For example,
#!/usr/bin/python3
a = ['a', 'b', 'a', 'a']
print(a.count("a"))
3
Important: this is very slow if you are counting multiple different items.
Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.
Using filter Method
You can use filter() function to count the occurrences of a list item, it really simple. For example,
#!/usr/bin/python3
a = ['a', 'b', 'a', 'a']
count = len(list(filter(lambda x: x=='a', a)))
print(count)
3
Using Counter Method
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
#!/usr/bin/python3
# Import module
from collections import Counter
a = ['a', 'b', 'a', 'a']
c = Counter(a)
print(c)
Counter({'a': 3, 'b': 1})
In Python, there are 3 ways to randomly select a element from list.
Using random.choice Method
The random.choice() method returns a random element from the non-empty sequence seq. If seq is empty, raises IndexError. For example,
#!/usr/bin/python3
# Import module
import random
a = ['a', 'b', 'c', 'd']
print(random.choice(a))
c
Using secrets.choice Method
For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice():
#!/usr/bin/python3
# Import module
import secrets
a = ['a', 'b', 'c', 'd']
print(secrets.choice(a))
b
Using random.sample Method
The sample method returns a new list containing elements from the population while leaving the original population unchanged.
#!/usr/bin/python3
# Import module
import random
a = ['a', 'b', 'c', 'd']
l = random.sample(a, 2)
print(l)
['b', 'a']
By default the random number generator uses the current system time.
In Python, there are 4 ways to know if an object has an attribute.
Using hasattr Method
The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
class Person:
age = 10
person = Person()
print(hasattr(person, "name"))
False
Using AttributeError Exception
Raised when an attribute reference or assignment fails.
For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
class Person:
age = 10
person = Person()
try:
person.name
# Exists
except AttributeError:
# Doesn't exist
print("Doesn't exist")
Doesn't exist
Using in Keyword
This approach has serious limitation. in keyword works for checking iterable types.
For example,
person = {
"age": 10
}
if 'age' in person:
print(person['age'])
10
Using dir Method
The method dir() returns a list of valid attributes for that object. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
#!/usr/bin/python3
# -*- coding: utf8 -*-
class Person:
age = 10
person = Person()
if 'age' in dir(person):
print(person.age)
10
In Golang, there are 2 ways to list all standard packages.
Using packages
go install
Use the following command to download the repository to the local file system.
install
go get golang.org/x/tools/go/packages
go install golang.org/x/tools/go/packages@latest
Note that since Go 1.17 installing packages with go get is deprecated:
packages Usage
Package packages loads Go packages for inspection and analysis.
For example,
package main
import (
"fmt"
"golang.org/x/tools/go/packages"
)
func main() {
pkgs, err := packages.Load(nil, "std")
if err != nil {
panic(err)
}
fmt.Println(pkgs)
}
[archive/tar bufio bytes...]
Using exec.Command Function
Use the go list std command to list the standard packages. The special import path std expands to all packages in the standard Go library.
See the following example:
package main
import (
"fmt"
"os/exec"
"strings"
)
func main() {
cmd := exec.Command("go", "list", "std")
o, err := cmd.Output()
if err != nil {
panic(err)
}
pkgs := strings.Fields(string(o))
fmt.Println(pkgs)
}
[archive/tar bufio bytes...]
In Golang, there are 3 ways to read a whole file into a string variable.
Using ioutil.ReadFile Function
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
As of Go 1.16, this function simply calls os.ReadFile.
For example,
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt")
if err != nil {
// panic()
}
s := string(b)
fmt.Println(s)
}
One
Two
Using bytes.ReadFrom Function
ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed.
See the following example:
package main
import (
"bytes"
"fmt"
"os"
)
func main() {
buf := bytes.NewBuffer(nil)
f, err := os.Open("file.txt")
if err != nil {
// panic()
}
defer f.Close()
// reads data
buf.ReadFrom(f)
s := buf.String()
fmt.Println(s)
}
One
Two
The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.
Using strings.Builder Function
A Builder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.
package main
import (
"fmt"
"io"
"os"
"strings"
)
func main() {
f, err := os.Open("file.txt")
if err != nil {
// panic()
}
defer f.Close()
// reads data
b := new(strings.Builder)
io.Copy(b, f)
s := b.String()
fmt.Println(s)
}
One
Two
In Golang, there are 3 ways to check the equality of two slices.
Using bytes.Equal Function
Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.
For example,
package main
import (
"bytes"
"fmt"
)
func main() {
a := []byte{1, 2, 3}
b := []byte{1, 2, 3}
fmt.Println(bytes.Equal(a, b))
}
true
Using reflect.DeepEqual Function
DeepEqual reports whether x and y are “deeply equal,” defined as follows.
See the following example:
package main
import (
"fmt"
"reflect"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
c := []int{1, 3, 2}
fmt.Println(reflect.DeepEqual(a, b))
// a[1] != c[1]
fmt.Println(reflect.DeepEqual(a, c))
}
true
false
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.
Using slices.Equal Function
Starting with Go 1.18, we can compare two slices easily using slices.Equal.
The slices package import path is golang.org/x/exp/slices. Code inside exp package is experimental, not yet stable. It could be moved to the standard library in Go 1.19.
// version 1.18+
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
a := []int{1, 2, 3}
b := []int{1, 2, 3}
fmt.Println(slices.Equal(a, b))
}
true
In Golang, using the delete function is the easiest way to delete keys in a map.
Using delete Function
Syntax
The syntax of the delete function is shown below.
func delete(m map[Type]Type1, key Type)
delete Usage
The delete built-in function deletes the element with the specified key (m[key]) from the map. If m is nil or there is no such element, delete is a no-op.
See the following example:
package main
import "fmt"
func main() {
m := map[string]int{
"a": 1,
"b": 1,
"c": 1,
"d": 1,
}
// To delete a map entry
delete(m, "c")
fmt.Println(m)
}
map[a:1 b:1 d:1]
In Python, there are 3 ways to remove an element from a list by index.
Using del Keyword
There is a way to remove an item from a list given its index instead of its value. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
del l[-1]
print(l)
# supports slices:
del l[1:3]
print(l)
[1, 2, 3]
[1]
del can also be used to delete entire variables.
Using pop Method
By default, pop without any arguments removes the last item:
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
l.pop()
print(l)
[1, 2, 3]
Using slices Operator
This does not do in place removal of item from original list.
For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
l = [1, 2, 3, 4]
# Only positive index
i = 2
l = l[:i]+l[i+1:]
print(l)
[1, 2, 4]
Please note that this method does not modify the list in place like pop and del. It instead makes two copies of lists and one after the index till the last element and creates a new list object by adding both.
In Python, there are 4 ways to limit floats to two decimal points.
Using format Method
You can use str.format() function to limit floats, it really simple. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
f = 13.949999999999999
print("{:.2f}".format(f))
print(format(f, '.2f'))
# to float
print(float("{:.2f}".format(f)))
13.95
13.95
13.95
Using F-strings
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.
#!/usr/bin/python3
# -*- coding: utf8 -*-
a = 13.949999999999999
print(f'{a:.2f}')
a = 2.675
print(f'{a:.2f}')
a = 2.675222
print(f'{a:.2f}')
13.95
2.67
2.68
Using round Method
Round a number to a given precision in decimal digits. If ndigits is omitted or is None, it returns the nearest integer to its input.
For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
print(round(13.949999999999999, 2))
print(round(2.675, 2))
print(round(2.675222, 2))
print(round(1.5, 2))
print(round(1.5))
13.95
2.67
2.68
1.5
2
Another form of exact arithmetic is supported by the fractions module which implements arithmetic based on rational numbers (so the numbers like 1/3 can be represented exactly).
Using int Method
You can do the same as:
#!/usr/bin/python3
# -*- coding: utf8 -*-
f = 13.949999999999999
b = int(f*100 + 0.5) / 100.0
print(b)
f = 2.675
b = int(f*100 + 0.5) / 100.0
print(b)
13.95
2.68
In Rust, there are 2 ways to concatenate vectors .
Using append Method
The method append() moves all the elements of other into Self, leaving other empty. See the following example:
fn main() {
let mut a = vec![1, 2];
let mut b = vec![3, 4];
a.append(&mut b);
println!("{:?}", a);
}
[1, 2, 3, 4]
Using extend Method
You can use extend() to extend a collection with the contents of an iterator:
fn main() {
let mut a = vec![1, 2];
let b = vec![3, 4];
a.extend(b);
println!("{:?}", a);
}
[1, 2, 3, 4]
In Rust, there are 3 ways to convert a string into a &'static str.
Using slicing Syntax
To go from a String to a slice &'a str you can use slicing syntax. See the following example:
// Rust 1.0+
fn main() {
let s: String = "abc".to_owned();
// take a full slice of the string
let slice: &str = &s[..];
println!("{}", slice);
}
abc
Using & Operator
You can use the fact that String implements Deref<Target=str> and perform an explicit reborrowing:
fn main() {
let s: String = "abc".to_owned();
// *s : str (via Deref<Target=str>)
// &*s: &str
let slice: &str = &*s;
println!("{}", slice);
}
abc
Using unsafe Code
As of Rust version 1.26, it is possible to convert a String to &'static str without using unsafe code:
// Rust 1.26+
fn string_to_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn main() {
let s: String = "abc".to_owned();
let slice: &str = string_to_str(s);
println!("{}", slice);
}
abc
In Rust, there are 2 ways to access command line parameters.
Using std::env::args Function
This function actually returns the arguments that this program was started with. See the following example:
use std::env;
fn main() {
for arg in env::args() {
println!("{}", arg)
}
// to Vec
let args: Vec<_> = env::args().collect();
println!("{}", args[0])
}
hello-rust
The first element is traditionally the path of the executable, but it can be set to arbitrary text, and might not even exist. This means this property should not be relied upon for security purposes.
Using docopt Library
Installation
This crate is fully compatible with Cargo. Just add it to your Cargo.toml:
[dependencies]
#Using Serde's derive
serde = { version = "1.0", features = ["derive"] }
docopt = "1"
docopt Usage
Here is a full working example. Notice that you can specify the types of each of the named values in the Docopt usage string. Values will be automatically converted to those types (or an error will be reported).
use docopt::Docopt;
use serde::Deserialize;
const USAGE: &'static str = "
Usage:
hello-rust <x> [--name=<nm>]
Options:
--name=<nm> Copy [default: Boo].
";
#[derive(Debug, Deserialize)]
struct Args {
flag_name: String,
arg_x: Option<i64>,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
println!("{:?}", args.flag_name);
println!("{:?}", args.arg_x);
}
"John"
Some(10)
In Golang, there are 3 ways to get the directory of the currently running file. Using os.Executable Function
Executable returns the path name for the executable that started the current process.
The easiest way to get the directory of the currently running file in Golang:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
exec, err := os.Executable()
if err != nil {
// panic()
}
dir := filepath.Dir(exec)
fmt.Println(dir)
}
/data/golang
Using os.Getwd Function
Getwd returns a rooted path name corresponding to the current directory. For example,
package main
import (
"fmt"
"os"
)
func main() {
pwd, err := os.Getwd()
if err != nil {
// panic()
}
fmt.Println(pwd)
}
/data/golang
Using Command-line Arguments
Command-line arguments are a common way to parameterize execution of programs. Sometimes this is enough, the first argument will always be the file path:
package main
import (
"fmt"
"os"
)
func main() {
path := os.Args[0]
fmt.Println(path)
}
./backend
Doesn't always work well.
In Golang, there are 2 ways to pretty-print json.
Using json.MarshalIndent Function
MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.
package main
import (
"encoding/json"
"fmt"
)
func main() {
str := `{"name":"Boo", "age":10}`
// parses the JSON-encoded data
var v map[string]interface{}
json.Unmarshal([]byte(str), &v)
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
// panic()
}
fmt.Println(string(b))
}
{
"age": 10,
"name": "Boo"
}
Using json.Indent Function
Indent appends to dst an indented form of the JSON-encoded src. You can use json.Indent function, it really simple. For example,
package main
import (
"bytes"
"encoding/json"
"fmt"
)
func main() {
str := `{"name":"Boo", "age":10}`
var out bytes.Buffer
err := json.Indent(&out, []byte(str), "", " ")
if err != nil {
// panic()
}
fmt.Println(string(out.Bytes()))
}
{
"name": "Boo",
"age": 10
}
In Python, there are 3 ways to list all files of a directory.
Using os.listdir Method
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. See the following example:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import os
path = "."
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
print(files)
['demo.py', 'start.sh', 'file.txt']
Using os.walk Method
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import os
path = "."
files = next(os.walk(path), (None, None, []))[2]
print(files)
['demo.py', 'start.sh', 'file.txt']
Using glob Module
The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import glob
txt = "*.txt"
files = glob.glob(txt)
print(files)
['file.txt']