All Go Rust Python PHP JavaScript
Chrome Dev Summit to secure your spot in workshops, office hours and learning lounges!

How to Execute a Program or Call a System Command in Python

In Python, there are 3 ways to execute a program or call a system command. Using subprocess Module The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import subprocess subprocess.run(["ls", "-l"]) ... file.txt On Python 3.4 and earlier, use subprocess.call instead of .run. Using os.system Method Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import os os.system("ls -l") ... file.txt Using subprocess.Popen Method Execute a child program in a new process. This is intended as a replacement for os.popen, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import subprocess out = subprocess.Popen("echo Hello", shell=True, stdout=subprocess.PIPE).stdout.read() print(out) b'Hello\n'
Patcher56

How to Remove Packages Installed with go get in Go

In Golang, there are 3 ways to remove packages installed with go get. Using go mod tidy go mod tidy ensures that the go.mod file matches the source code in the module. It adds any missing module requirements necessary to build the current module’s packages and dependencies, and it removes requirements on modules that don’t provide any relevant packages. It also adds any missing entries to go.sum and removes unnecessary entries. mod go mod tidy Using rm Command It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/. Using @none Version A go package can be removed as follows: Removing go get package@none
ada

How to Get a Slice of Keys from a Map in Go

In Golang, there are 3 ways to get a slice of keys from a map. Using For Range The easiest way to get keys of map in Golang: package main import "fmt" func main() { m := map[string]int{ "a": 1, "b": 1, "c": 1, } // minimize memory allocations keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } fmt.Printf("%q\n", keys) } ["c" "a" "b"] To be efficient in Go, it's important to minimize memory allocations. Using maps.Keys Function Keys returns the keys of the map m. The keys will be in an indeterminate order. Go now has generics starting with version 1.18. We can get the keys of any map with maps.Keys. The following example: // version 1.18+ package main import ( "fmt" "golang.org/x/exp/maps" ) func main() { m := map[string]int{ "a": 1, "b": 1, "c": 1, } // using 1.18 or later keys := maps.Keys(m) fmt.Printf("%q\n", keys) } ["c" "a" "b"] maps package is found in golang.org/x/exp/maps. This is experimental and outside of Go compatibility guarantee. They aim to move it into the std lib in Go 1.19. Using reflect Package You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect": package main import ( "fmt" "reflect" ) func main() { m := map[string]int{ "a": 1, "b": 1, "c": 1, } keys := reflect.ValueOf(m).MapKeys() fmt.Printf("%q\n", keys) } ["b" "c" "a"]
Sambhav Khandelwal

How to Split a String in Rust

In Rust, there are 3 ways to split a string. Using split Function An iterator over substrings of this string slice, separated by characters matched by a pattern. See the following example: fn main() { let s = "abc1bcd2e"; let _split = s.split("b"); let _v = s.split(char::is_numeric); let _v = s.split(char::is_uppercase); // complex pattern let v = s.split(|c| c == '1' || c == 'd'); for m in v { println!("{}", m); } } abc bc 2e See split for more information. Using lines Function You can use lines() function to split a string, it really simple. For example, fn main() { let s = "abc\r\nbc\nd2"; let lines = s.lines(); for m in lines { println!("{}", m); } } abc bc d2 Lines are ended with either a newline (\n) or a carriage return with a line feed (\r\n). Using regex.split Function Usage Adding regex to your dependencies in your project’s Cargo.toml. [dependencies] regex = "1" Example: split a string The split returns an iterator of substrings of text delimited by a match of the regular expression. Namely, each element of the iterator corresponds to text that isn't matched by the regular expression. use regex::Regex; fn main() { let s = "abc\tbc d2"; let re = Regex::new(r"[ \t]").unwrap(); let lines: Vec = re.split(s).collect(); for m in lines { println!("{}", m); } } abc bc d2
ada

How to Concatenate Strings in Rust

In Rust, there are 4 ways to concatenate strings. Using String.push_str Function This function actually appends a given string slice onto the end of this `String`. See the following example: fn main() { let mut s1: String = "Hello ".to_owned(); let s2: &str = "world"; s1.push_str(s2); println!("{}", s1); } Hello world This is efficient as it potentially allows us to reuse the memory allocation. Using + Operator This is an implementation of the Add trait that takes a String as the left-hand side and a &str as the right-hand side: fn main() { let s1: String = "Hello ".to_owned(); let s2: &str = "world"; // borrow of moved value: `s1` // `s1` is moved and can no longer be used here. let s = s1 + s2; println!("{}", s); // value borrowed here after move // println!("{}", s1); // let s = s1.clone() + s2; } Hello world If you want to keep using the first String, you can clone it and append to the clone instead. Using format! Function What if we wanted to produce a new string, The simplest way is to use format!: fn main() { let s1: String = "Hello ".to_owned(); let s2: &str = "world"; let s = format!("{}{}", s1, s2); println!("{}", s); } Hello world Using concat! Function You can use concat!() function to concatenate literals into a static string slice. it really simple. For example, fn main() { let s = concat!("Hello ", "world ", 1); println!("{}", s); } Hello world 1
Tomoki

How to Make a Time Delay in Python

In Python, there are 2 ways to make a time delay. Using time.sleep Function This function actually suspends execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import time # def sleep(secs: float) -> None time.sleep(0.5) 2022-04-27 10:48:46.195335 2022-04-27 02:48:46.195834+00:00 Using threading.Timer Objects This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads. like this: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module from threading import Timer sec = 2 def hello(in_sec): print(f'function called {in_sec} s') t = Timer(sec, hello, [sec]) # Start the thread's activity. t.start() function called 2 s Timers are started, as with threads, by calling their start() method. It does not stop execution of the whole script (except for the function you pass it).
aweis

How to Get the Current Time in Python

In Python, there are 2 ways to get the current time. Using datetime Module The datetime module supplies classes for manipulating dates and times. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import datetime from zoneinfo import ZoneInfo now = datetime.datetime.now() print(now) tz = ZoneInfo("Etc/UTC") utc = datetime.datetime.now(tz=tz) print(utc) 2022-04-27 10:48:46.195335 2022-04-27 02:48:46.195834+00:00 Construct a datetime from time.time() and optional time zone info. Using time Module You can use time.gmtime() method to convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import time # time.gmtime([secs]) now = time.gmtime() f = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) print(f) 2022-04-27 02:58:35 This is UTC time, different from datetime module. Use the function localtime() instead of the gmtime() to get your local time. time.strftime Method The following directives can be embedded in the format string: Directives: %aLocale’s abbreviated weekday name.%ALocale’s full weekday name.%bLocale’s abbreviated month name.%BLocale’s full month name.%cLocale’s appropriate date and timerepresentation.%dDay of the month as a decimal number [01,31].%HHour (24-hour clock) as a decimal number[00,23].%IHour (12-hour clock) as a decimal number[01,12].%jDay of the year as a decimal number [001,366].%mMonth as a decimal number [01,12].%MMinute as a decimal number [00,59].%pLocale’s equivalent of either AM or PM.%SSecond as a decimal number [00,61].%UWeek number of the year (Sunday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstSunday are considered to be in week 0.%wWeekday as a decimal number [0(Sunday),6].%WWeek number of the year (Monday as the firstday of the week) as a decimal number [00,53].All days in a new year preceding the firstMonday are considered to be in week 0.%xLocale’s appropriate date representation.%XLocale’s appropriate time representation.%yYear without century as a decimal number[00,99].%YYear with century as a decimal number.%zTime zone offset indicating a positive ornegative time difference from UTC/GMT of theform +HHMM or -HHMM, where H represents decimalhour digits and M represents decimal minutedigits [-23:59, +23:59].%%A literal '%' character.
Patcher56

How to Convert String to Bytes in Go

In Golang, there are 2 ways to assign string to bytes. Using byte Function The easiest way to convert string to []byte in Golang: package main import "fmt" func main() { s := "Hello" b := []byte(s) fmt.Printf("%v\n", b) } [72 101 108 108 111] Using copy Function The copy built-in function copies elements from a source slice into a destination slice. You can use copy function to assign string to bytes. The following example: package main import "fmt" func main() { s := "Hello" b := [3]byte{} copy(b[:], s) fmt.Printf("%v\n", b) c := [7]byte{} copy(c[:], s) fmt.Printf("%v\n", c) } [72 101 108] [72 101 108 108 111 0 0] If the string is too long, copy will only copy the part of the string that fits (and multi-byte runes may then be copied only partly, which will corrupt the last rune of the resulting string).
Tomoki

How to Merge two Dictionaries into a new Dictionary in Python

In Python, there are 3 ways to merge two dictionaries into a new dictionary. Using Additional Unpacking Generalizations Starting with Python 3.5, we can merge in with literal notation as well. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- x = {"a": 1, "b": 2} y = {"a": 3, "c": 4} # dictionary unpacking operators z = {**x, **y} print(z) {'a': 3, 'b': 2, 'c': 4} In dictionaries, later values will always override earlier ones. Using | Operator In Python 3.9.0 or greater, dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict. If a key appears in both operands, the last-seen value wins. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- x = {"a": 1, "b": 2} y = {"a": 3, "c": 4} # Add Union Operators To dict z = x | y print(z) # The augmented assignment version operates in-place: x |= y print(x) {'a': 3, 'b': 2, 'c': 4} {'a': 3, 'b': 2, 'c': 4} Using ChainMap Method Uou can use collections.ChainMap which groups multiple dicts or other mappings together to create a single, try this: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import collections x = {"a": 1, "b": 2} y = {"a": 3, "c": 4} z = dict(collections.ChainMap(x, y)) print(z) {'a': 1, 'c': 4, 'b': 2}
Unused

How to Check whether a File Exists in Python

In Python, there are 3 ways to check if a file exists. Using os.path.exists Method Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import os if os.path.exists("file.txt"): print("File exists") # --- Source Code --- # def exists(path): # """Test whether a path exists. Returns False for broken symbolic links""" # try: # os.stat(path) # except (OSError, ValueError): # return False # return True File exists This returns True for both files and directories. Using os.path.isfile Method Return True if path is an existing regular file. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import os # os.path.isdir if not os.path.isfile("f.txt"): print("File does not exist") File does not exist Using pathlib Module Starting with Python 3.4, the pathlib module offers an object-oriented approach, try this: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import pathlib f = pathlib.Path("file.txt") # f.is_dir() f.exists() if f.is_file(): print("File exists") File exists
Patcher56

How to Convert Byte Array to String in Go

In Golang, there are 2 ways to convert byte array to string. Using string Function The easiest way to convert []byte to string in Golang: package main import "fmt" func main() { b := []byte{'a', 'b', 'c'} s := string(b[:]) fmt.Printf("%q\n", s) } "abc" Using fmt.Sprintf Function You can use fmt.Sprintf function to convert byte array to string. The following example: package main import "fmt" func main() { b := []byte{'a', 'b', 'c'} s := fmt.Sprintf("%s", b) fmt.Printf("%q\n", s) } "abc" a zero-terminated byte array If you want to convert a zero-terminated byte array to string. See the following example: package main import ( "bytes" "fmt" ) func main() { b := [5]byte{'a', 'b', 'c'} s := string(b[:]) fmt.Printf("%q length:[%d]\n", s, len(s)) // remove zero-terminated byte n := bytes.Index(b[:], []byte{0}) s = string(b[:n]) fmt.Printf("%q length:[%d]\n", s, len(s)) } "abc\x00\x00" length:[5] "abc" length:[3]
Tomoki

How to Concatenate Two Slices in Go

In Golang, there are 2 ways to concatenate two slices. Using append Function The append built-in function appends elements to the end of a slice. You can use append function, it really simple. For example, package main import "fmt" func main() { s1 := []string{"a", "b"} s2 := []string{"a", "c"} // slice = append(slice, anotherSlice...) s := append(s1, s2...) fmt.Printf("%q\n", s) // slice = append(slice, elem1, elem2) s = append(s1, s2[0], s2[1]) fmt.Printf("%q\n", s) } ["a" "b" "a" "c"] ["a" "b" "a" "c"] Using Full Slice Expression You can use a full slice expression which has the form a[low : high : max], which constructs a slice and also controls the resulting slice's capacity by setting it to max - low. The following example: package main import "fmt" // For generics (if using 1.18 or later) func concat[T any](s1 []T, s2 []T) []T { n := len(s1) return append(s1[:n:n], s2...) } func main() { s1 := []string{"a", "b"} s2 := []string{"a", "c"} s := append(s1[:2:2], s2...) fmt.Printf("%q\n", s) s = concat(s1, s2) fmt.Printf("%q\n", s) } ["a" "b" "a" "c"] ["a" "b" "a" "c"]
aweis

How to Check if a File Exists in Go

In Golang, there are 2 ways to check if a file exists. Using os.Stat Function Stat returns a FileInfo describing the named file. See the following example: package main import ( "errors" "fmt" "os" ) func main() { // since the addition of errors.Is in Go 1.13 (released in late 2019) if _, err := os.Stat("f.txt"); errors.Is(err, os.ErrNotExist) { fmt.Println(err) } } stat f.txt: no such file or directory To check if a file doesn't exist, equivalent to Python's if not os.path.exists(filename). Using os.Open Function Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError. For example, package main import ( "errors" "fmt" "os" ) func main() { if _, err := os.Open("f.txt"); errors.Is(err, os.ErrNotExist) { fmt.Println(err) } } open f.txt: no such file or directory
aweis

How to Read a File Line-by-Line in Go

In Golang, there are 2 ways to read a file line-by-line. Using bufio.Scanner Function Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text. The ones that are currently implemented are: package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { // panic() } defer f.Close() scanner := bufio.NewScanner(f) scanner.Split(bufio.ScanLines) for scanner.Scan() { fmt.Println(scanner.Text()) } } One Two There is one caveat: Scanner will error with lines longer than 65536 characters. If you know your line length is greater than 64K, use the Buffer() method to increase the scanner's capacity: package main import ( "bufio" "fmt" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { // panic() } defer f.Close() scanner := bufio.NewScanner(f) const max int = 1024 buf := make([]byte, max) scanner.Buffer(buf, max) for scanner.Scan() { fmt.Println(scanner.Text()) } } One Two Using bufio.ReadString Function ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim. For simple uses, a Scanner may be more convenient. For example, package main import ( "bufio" "fmt" "io" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { // panic() } defer f.Close() rd := bufio.NewReader(f) for { // 0x0A separator = newline line, err := rd.ReadString(10) // Trim // line = strings.TrimSpace(line) fmt.Println(line) if err != nil { if err == io.EOF { break } // panic() return error } } // End for } One Two
Sambhav Khandelwal

How to Remove Duplicates Strings from Slice in Go

In Golang, there are 2 ways to remove duplicates strings from slice. Using a Hash Map We have defined a function where we are passing the slice values and using the map function we are checking the duplicates and removing them. The ones that are currently implemented are: package main import "fmt" func removeDuplicates(s []string) []string { // Hash Map m := make(map[string]struct{}) list := []string{} for _, v := range s { if _, ok := m[v]; !ok { m[v] = struct{}{} list = append(list, v) } } return list } func main() { s := []string{"a", "b", "a", "c"} n := removeDuplicates(s) fmt.Printf("%q\n", n) } ["a" "b" "c"] You can update the slice type, and it will filter out all duplicates data for all types of slices. You can do in-place replacement guided with a map: package main import "fmt" func removeDuplicates(s []string) []string { // Hash Map m := make(map[string]struct{}) w := 0 for _, v := range s { if _, ok := m[v]; !ok { m[v] = struct{}{} s[w] = v w++ } } return s[:w] } func main() { s := []string{"a", "b", "a", "c"} n := removeDuplicates(s) fmt.Printf("%q\n", n) } ["a" "b" "c"] Using sort.Strings Function You can use sort.Strings() function, it really simple. For example, package main import ( "fmt" "sort" ) func removeDuplicates(s []string) []string { if len(s) < 1 { return s } sort.Strings(s) w := 1 for i := 1; i < len(s); i++ { if s[i-1] != s[i] { s[w] = s[i] w++ } } return s[:w] } func main() { s := []string{"a", "b", "a", "c"} n := removeDuplicates(s) fmt.Printf("%q\n", n) } ["a" "b" "c"] Strings sorts a slice of strings in increasing order.
pooriabt

How To Generate a Random String in Python

In Python, there are 3 ways to generate a random string. Using List Comprehension List comprehensions provide a concise way to create lists. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import random import string # a string of size n letters = string.ascii_letters n = 6 lst = ''.join(random.choice(letters) for i in range(n)) print(lst) nYVWGX uUeAAJ Using random.choices Function Starting with Python 3.6 using random.choices(). For example, #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import random import string # a string of size n letters = string.ascii_letters n = 6 lst = ''.join(random.choices(letters, k=n)) print(lst) Gzmslz gdESzU From Python 3.6, random.choices would be faster. random.choice is not secure either. Use random.SystemRandom().choice() or use os.urandom() directly. #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import random import string # a string of size n letters = string.ascii_letters n = 6 lst = ''.join(random.SystemRandom().choices(letters, k=n)) print(lst) wxTUTI QwBInx Using uuid Module This module provides immutable UUID objects. uuid4() creates a random UUID. If UUIDs are okay for your purposes, use the built-in uuid package. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import uuid # a string of size n n = 6 lst = uuid.uuid4().hex[0:n] print(lst) 465fc7 fbcccb
Sambhav Khandelwal

How To Convert string to integer in Python

In Python, there are 2 ways to convert string to int. Using int Built-in Function Return an integer object constructed from a number or string x, or return 0 if no arguments are given. #!/usr/bin/python3 # -*- coding: utf8 -*- s = "100" # class int(x, base=10) i = int(s) print(i) print(type(i)) 100 <class 'int'> Python different number data types: long() float() complex(). Convert with different bases If the String you want to convert into int belongs to a different number base other than base 10, you can specify that base for that conversion. See the following example: #!/usr/bin/python3 # -*- coding: utf8 -*- s = "101010" i = int(s) print(i) # base binary i = int(s, 2) print(i) print(type(i)) # a binary string print(bin(42)) 101010 42 <class 'int'> 0b101010 Python error: invalid literal for int() with base 10. #!/usr/bin/python3 # -*- coding: utf8 -*- s = "a1f" i = int(s) print(i) ValueError: invalid literal for int() with base 10: 'a1f' a hexadecimal string, #!/usr/bin/python3 # -*- coding: utf8 -*- s = "a1f" # base hexadecimal i = int(s, 16) print(i) print(type(i)) # a hexadecimal string print(hex(2591)) 2591 <class 'int'> 0xa1f
aweis

How to find the intersection between two lists in Python

In Python, there are 4 ways to find the intersection between two lists. Using Set Intersection A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. #!/usr/bin/python3 # -*- coding: utf8 -*- l1 = ["a", "b", "c"] l2 = ["b", "a", "C"] lst = list(set(l1) & set(l2)) print(lst) # Sets A = {"a", "b", "c"} B = {"b", "a", "C"} # A & B print(A & B) # B & A print(B & A) ['b', 'a'] {'b', 'a'} {'b', 'a'} This will remove the duplicates in each list. Using intersection Method Return a new set with elements common to the set and all others. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- l1 = ["a", "b", "c"] l2 = ["b", "a", "C"] lst = list(set(l1).intersection(l2)) print(lst) ['b', 'a'] Using List Comprehension If you want to preserve order of input list, try this: #!/usr/bin/python3 # -*- coding: utf8 -*- a = ["a", "b", "c"] b = ["b", "a", "C"] # for loop s = set(b) lst = [x for x in a if x in s] print(lst) ['a', 'b'] This is an O(n) solution, faster than O(n*m) performance. Using lambda Operator It can be achieved using filter and lambda operator. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- a = ["a", "b", "c"] b = ["b", "a", "C"] # for loop lst = list(filter(lambda x:x in a, b)) print(lst) ['b', 'a']
Unused

How to find the difference between two lists in Python

In Python, there are 5 ways to find the difference between two lists. Using Set Difference A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. #!/usr/bin/python3 # -*- coding: utf8 -*- l1 = ["a", "b", "c"] l2 = ["b", "C"] lst = list(set(l1) - set(l2)) print(lst) # Sets A = {"a", "b", "c"} B = {"b", "C"} # A - B print(A-B) # B - A print(B-A) ['a', 'c'] {'a', 'c'} {'C'} This will remove the duplicates in each list. Using difference Method Return a new set with elements in the set that are not in the others. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- l1 = ["a", "b", "c"] l2 = ["b", "C"] lst = list(set(l1).difference(l2)) print(lst) ['a', 'c'] Returns the new slice of filtered values. Using XOR Operator Return the bitwise exclusive or of a and b. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- a = ["a", "b", "c"] b = ["b", "C"] # xor operator lst = list(set(a) ^ set(b)) print(lst) ['c', 'a', 'C'] This will show difference of a from b and b from a. Using List Comprehension If you want to preserve order of input list, try this: #!/usr/bin/python3 # -*- coding: utf8 -*- a = ["a", "b", "c"] b = ["b", "C"] # for loop s = set(b) lst = [x for x in a if x not in s] print(lst) ['c', 'a', 'C'] This is an O(n) solution, faster than O(n*m) performance. Using lambda Operator It can be achieved using filter and lambda operator. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- a = ["a", "b", "c"] b = ["b", "a", "C"] # for loop lst = list(filter(lambda x:x not in a, b)) print(lst) ['C']
Sambhav Khandelwal

How To Read a File Line-by-Line in Rust

In this program, we will open a text file and read the file line by line and print the result.Using lines Method The method lines() returns an iterator over the lines of a file. The following example: use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; fn main() { if let Ok(lines) = read_lines("file.txt") { for line in lines { if let Ok(text) = line { println!("{}", text) } } } } // The output is wrapped in a Result to allow matching on errors // Returns an Iterator to the Reader of the lines of the file. fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { // open a file in read-only mode let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } First line. Second line.
Patcher56

How To Split a list into equally sized chunks in Python

In Python, there are 3 ways to split a list into equally sized chunks. Using List Comprehension List comprehensions provide a concise way to create lists. The following example: #!/usr/bin/python3 # -*- coding: utf8 -*- # initialize lst = ['a'] * 7 # chunks n = 3 a = [lst[i:i+n] for i in range(0, len(lst), n)] print(a) [['a', 'a', 'a'], ['a', 'a', 'a'], ['a']] Using yield The yield keyword enables a function to comeback where it left off when it is called again. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- def chunks(l, n): for i in range(0, len(l), n): yield l[i:i+n] # initialize lst = ['a'] * 7 # chunks n = 3 a = list(chunks(lst, n)) print(a) [['a', 'a', 'a'], ['a', 'a', 'a'], ['a']] Using NumPy Module NumPy is the fundamental package for scientific computing in Python. If you use pip, you can install NumPy with: pip pip install numpy pip3 install numpy #!/usr/bin/python3 # -*- coding: utf8 -*- # Import module import numpy as np # initialize lst = ['a'] * 7 a = np.array_split(lst, 3) print(a) [['a' 'a' 'a'],['a' 'a'],['a' 'a']] numpy.array_split split an array into multiple sub-arrays. For an array of length l that should be split into n sections, it returns l % n sub-arrays of size l//n + 1 and the rest of size l//n.
Patcher56

How To Install Go in Linux

In Golang, there are 2 ways to install Go in Linux. Download Packages Download packages for Windows 64-bit, macOS, Linux, and more. Go install Linux Remove any previous Go installation by deleting the /usr/local/go folder (if it exists), then extract the archive you just downloaded into /usr/local, creating a fresh Go tree in /usr/local/go: install rm -rf /usr/local/go && tar -C /usr/local -xzf go1.18.1.linux-amd64.tar.gz Add /usr/local/go/bin to the PATH environment variable. You can do this by adding the following line to your $HOME/.profile or /etc/profile (for a system-wide installation): #sudo vi /etc/.profile #source /etc/.profile export PATH=$PATH:/usr/local/go/bin go sudo vi /etc/.profile source /etc/.profile go version go version go1.18.1 linux/amd64 Mac Open the package file you downloaded and follow the prompts to install Go. The package installs the Go distribution to /usr/local/go. The package should put the /usr/local/go/bin directory in your PATH environment variable. You may need to restart any open Terminal sessions for the change to take effect. Windows Open the MSI file you downloaded and follow the prompts to install Go. Installing Go from source Most users don't need to do this, and will instead install from precompiled binary packages as described in Download and install. See: Installing Go from source Try Go Online You can try Go online in the Go Playground without installing anything on your computer. See: TRY GO WITHOUT INSTALLING Go Help Commands and Options Go is a tool for managing Go source code. The commands are:bugstart a bug reportbuildcompile packages and dependenciescleanremove object files and cached filesdocshow documentation for package or symbolenvprint Go environment informationfixupdate packages to use new APIsfmtgofmt (reformat) package sourcesgenerategenerate Go files by processing sourcegetadd dependencies to current module and install theminstallcompile and install packages and dependencieslistlist packages or modulesmodmodule maintenanceruncompile and run Go programtesttest packagestoolrun specified go toolversionprint Go versionvetreport likely mistakes in packages Use "go help <command>" for more information about a command. Additional help topics:buildconstraintbuild constraintsbuildmodebuild modesccalling between Go and Ccachebuild and test cachingenvironmentenvironment variablesfiletypefile typesgo.modthe go.mod filegopathGOPATH environment variablegopath-getlegacy GOPATH go getgoproxymodule proxy protocolimportpathimport path syntaxmodulesmodules, module versions, and moremodule-getmodule-aware go getmodule-authmodule authentication using go.sumpackagespackage lists and patternsprivateconfiguration for downloading non-public codetestflagtesting flagstestfunctesting functionsvcscontrolling version control with GOVCS Use "go help <topic>" for more information about that topic.
Unused

How To Make a For Loop and Range in Rust

In Rust, there are 3 ways to support For Loop expression. Using while Expression A while loop begins by evaluating the boolean loop conditional operand. fn main() { let mut i = 0; while i < 3 { println!("{}", i); i += 1; } // Vec let mut x = vec![1, 2, 3]; while let Some(y) = x.pop() { println!("{}", y) } // Empty // warning: irrefutable `while let` pattern while let _ = 5 { // do Something break; } } 0 1 2 3 2 1 Using for Pattern in Expression A for expression is a syntactic construct for looping over elements provided by an implementation of std::iter::IntoIterator. For example, fn main() { let v = &["Apple", "Google"]; for text in v { println!("{}", text) } // a series of integers for i in 1..3 { println!("{}", i) } } Apple Google 1 2 Using loop Expression A loop expression denotes an infinite loop. For example, fn main() { // loop expression loop { println!("Infinite loops"); break; } // Result let mut i = 0; let result = loop { if i >= 3 { break i; } i += 1; println!("Infinite"); }; println!("{}", result); } Infinite loops Infinite Infinite Infinite 3 Range expressions Examples: fn main() { // Range expressions // 1..2; // std::ops::Range // 3..; // std::ops::RangeFrom // ..4; // std::ops::RangeTo // ..; // std::ops::RangeFull // 5..=6; // std::ops::RangeInclusive // ..=7; // std::ops::RangeToInclusive let x = std::ops::Range { start: 0, end: 2 }; let y = 0..2; for i in y { println!("{}", i) } } 0 1 The .. and ..= operators will construct an object of one of the std::ops::Range (or core::ops::Range) variants, according to the following table: Syntaxstart..endstd::ops::Range start ≤ x start..std::ops::RangeFrom start ≤ x..endstd::ops::RangeTo x ..std::ops::RangeFull -start..=endstd::ops::RangeInclusive start ≤ x ≤ end..=endstd::ops::RangeToInclusive x ≤ end
ada

How to check if key exists in HashMap in Rust

In Rust, there are 2 ways to check if key exists in HashMap. Using HashMap::contains_key Method The contains_key method return true if the map contains a value for the specified key. use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert("name", "John"); println!("{}", map.contains_key("name")) } true The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type. Numeric Keys Example, use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert(1, "age"); println!("{}", map.contains_key(&6)); println!("{}", map.contains_key(&1)); } false true Using the Eq Trait If you cannot use the derive strategy, specify that your type implements Eq, which has no methods: use std::collections::HashMap; use std::hash::{Hash, Hasher}; struct Book { isbn: i64, title: String, } impl Hash for Book { fn hash(&self, state: &mut H) { self.isbn.hash(state); // self.title.hash(state); } } impl PartialEq for Book { fn eq(&self, other: &Self) -> bool { self.isbn == other.isbn } } impl Eq for Book {} fn main() { let mut map: HashMap = HashMap::new(); map.insert( Book { isbn: 1, title: "Apple".to_string(), }, "Book".to_string(), ); // true let key = Book { isbn: 1, title: "Google".to_string(), }; println!("{}", map.contains_key(&key)); // false let key2 = Book { isbn: 2, title: "Google".to_string(), }; println!("{}", map.contains_key(&key2)); } true false
Unused

How to Read a File Line-by-Line in Python

In Python, there are 3 ways to read a file line-by-line. Using For Loop For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: #!/usr/bin/python3 # -*- coding: utf8 -*- # read all the lines of a file with open("file.txt", "r") as f: for line in f: print(line, end='') First line. Second line. Using f.readlines Method You can use f.readlines() to read all the lines of a file in a list. #!/usr/bin/python3 # -*- coding: utf8 -*- # read all the lines of a file with open("file.txt", "r") as f: lines = f.readlines() for line in lines: # remove all whitespace characters line = line.rstrip() print(line) # read a single line with open("file.txt", "r") as f: line = f.readline() print(line, end='') First line. Second line. First line. A newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. Using list Method For example, #!/usr/bin/python3 # -*- coding: utf8 -*- # read all the lines of a file with open("file.txt", "r") as f: for line in list(f): print(line, end='') First line. Second line. The Available Open Modes mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. modes'r'open for reading (default)'w'open for writing, truncating the file first'x'open for exclusive creation, failing if the file already exists'a'open for writing, appending to the end of file if it exists'b'binary mode't'text mode (default)'+'open for updating (reading and writing)
pooriabt

How to convert string to json in Rust

In Rust, there are 3 ways to convert string to json. Using Serde JSON Serde is a framework for serializing and deserializing Rust data structures efficiently and generically. Adding dependencies In Cargo.toml file we’ll add this information. [dependencies] #Using Serde's derive serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" Operating on untyped JSON values Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value. enum Value { Null, Bool(bool), Number(Number), String(String), Array(Vec), Object(Map), } For example, use serde_json::Value; use std::error::Error; fn main() -> Result> { let s = r#" { "name":"John", "age": 43, "ids": [3, 4, 5] }"#; // Parse the string of data into serde_json::Value. let v: Value = serde_json::from_str(s)?; println!("name:{} id0:{}", v["name"], v["ids"][0]); Ok(()) } name:"John" id0:3 Parsing JSON as strongly typed data structures Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically. use serde::{Deserialize, Serialize}; use std::error::Error; #[derive(Serialize, Deserialize)] struct Person { name: String, age: u8, ids: Vec, } fn main() -> Result> { let s = r#" { "name":"John", "age": 43, "ids": [3, 4, 5] }"#; // Parse the string of data into a Person object. let v: Person = serde_json::from_str(s)?; println!("name:{} id0:{}", v.name, v.ids[0]); Ok(()) } name:"John" id0:3 Using json! macro Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax. use serde_json::json; use std::error::Error; fn main() -> Result> { let v = json!( { "name":"John", "age": 43, "ids": [3, 4, 5] }); println!("name:{} id0:{}", v["name"], v["ids"][0]); Ok(()) } name:"John" id0:3 Serializing data structures A data structure can be converted to a JSON string by serde_json::to_string. use serde::{Deserialize, Serialize}; use std::error::Error; #[derive(Serialize, Deserialize)] struct Person { name: String, age: u8, ids: Vec, } fn main() -> Result> { let v = Person { name: "Jhon".to_string(), age: 10, ids: vec![3, 4, 5], }; let s = serde_json::to_string(&v)?; println!("{}", s); Ok(()) } {"name":"Jhon","age":10,"ids":[3,4,5]}
Patcher56

How to print a formatted string in Rust

Rust String Formatting and Printing Best Practices. Using println! Prints to the standard output, with a newline. Use the format! syntax to write data to the standard output. See std::fmt for more information. fn main() { let name = "Bob"; println!("Hello, {}", "World"); println!("{:?}", ("H", 4)); println!("{:04}", 12); println!("{1} {0}", "a", 13); println!("Hello {name}"); println!("{:0width$}", 12, width = 5); } Hello, World ("H", 4) 0012 13 a Hello Bob 00012 Example See: fn main() { // Precision println!("Float, {:.5}", 0.23); println!("Float, {:>7.2}", 0.23); println!("Float, {:.*}", 5, 0.23); println!("Float, {num:.prec$}", prec = 5, num = 0.23); // Escaping println!("Hello {{}}"); println!("Hello {{"); } Float, 0.23000 Float, 0.23 Float, 0.23000 Float, 0.23000 Hello {} Hello { Related macros There are a number of related macros in the format! family. The ones that are currently implemented are: format! // described above write! // first argument is a &mut io::Write, the destination writeln! // same as write but appends a newline print! // the format string is printed to the standard output println! // same as print but appends a newline eprint! // the format string is printed to the standard error eprintln! // same as eprint but appends a newline format_args! // described below. Formatting Parameters Each argument being formatted can be transformed by a number of formatting parameters. Fill/Alignmentthe argument is left-aligned in width columns^the argument is center-aligned in width columns>the argument is right-aligned in width columns Sign/#/0+This is intended for numeric types and indicates that the sign should always be printed. Positive signs are never printed by default, and the negative sign is only printed by default for signed values. This flag indicates that the correct sign (+ or -) should always be printed.-Currently not used#This flag indicates that the “alternate” form of printing should be used. The alternate forms are:#?pretty-print the Debug formatting (adds linebreaks and indentation)#xprecedes the argument with a 0x#Xprecedes the argument with a 0x#bprecedes the argument with a 0b#oprecedes the argument with a 0o0This is used to indicate for integer formats that the padding to width should both be done with a 0 character as well as be sign-aware. Precision.Nthe integer N itself is the precision..N$use format argument N (which must be a usize) as the precision..*.* means that this {...} is associated with two format inputs rather than one: the first input holds the usize precision, and the second holds the value to print. Formatting traits?Debugx?Debug with lower-case hexadecimal integersX?Debug with upper-case hexadecimal integersoOctalxLowerHexXUpperHexpPointerbBinaryeLowerExpEUpperExp
aweis

Rust error: cannot assign twice to immutable variable

In Rust, variables by default are immutable. Variables Immutable You can make them mutable by adding mut in front of the variable name. For example, fn main() { let x = 2; println!("value x: {}", x); x = 4; println!("value x: {}", x); } error[E0384]: cannot assign twice to immutable variable `x` --> src/main.rs:5:3 | 2 | let x = 2; | - | | | first assignment to `x` | help: consider making this binding mutable: `mut x` ... 5 | x = 4; | ^^^^^ cannot assign twice to immutable variable For more information about this error, try `rustc --explain E0384`. error: could not compile `hello-rust` due to previous error Save and run the program using cargo run. You should receive an error message. Variables Mutable When a variable is immutable, once a value is bound to a name, you can’t change that value. For example, fn main() { let mut x = 2; println!("value x: {}", x); x = 4; println!("value x: {}", x); } value x: 2 value x: 4 Mismatched Types For example, fn main() { let mut s = "abcd"; // mutate a variable’s type s = s.len() } error[E0308]: mismatched types --> src/main.rs:3:7 | 2 | let mut s = "abcd"; | ------ expected due to this value 3 | s = s.len() | ^^^^^^^ expected `&str`, found `usize` For more information about this error, try `rustc --explain E0308`. error: could not compile `hello-rust` due to previous error
Patcher56

How to create a multiline string in Rust

In Rust, there are 4 ways to create multiple lines string. Using triple-quotes A string literal is a sequence of any Unicode characters enclosed within two U+0022 (double-quote) characters, with the exception of U+0022 itself, which must be escaped by a preceding U+005C character (\). The following example: fn main() { // Backslash line brea let s = "Apple \ Google \ Twitter"; println!("{}", s); // unnecessary spaces let s1 = "Apple Google Twitter"; println!("{}", s1); } Apple Google Twitter Apple Google Twitter Using Raw string literals Raw string literals do not process any escapes. They start with the character U+0072 (r), followed by zero or more of the character U+0023 (#) and a U+0022 (double-quote) character. For example, fn main() { // Raw string literals let s = r#"Apple Google Twitter"#; println!("{}", s); } Apple Google Twitter you can denote an arbitrary number of hashes as a delimiter: fn main() { // Raw string literals let s = r###"Apple Google ##"# Twitter"###; println!("{}", s); } Apple Google ##"# Twitter Using concat Method You can use the concat! macro. It concatenates string literals at compile time. For example, fn main() { // concat let s = concat!( "Apple", 10, true ); println!("{}", s); } Apple10btrue
Unused

How to check if string contains substring in Rust

In Rust, there are 3 ways to check if string contains substring. Using String contains Function The easiest way to check if a Rust string contains a substring is to use String::contains method. The contains method Returns true if the given pattern matches a sub-slice of this string slice. fn main() { let s = "Apple,世界"; // pub fn contains(&'a self, pat: P) -> bool println!("{}", s.contains("e")); println!("{}", s.contains("世")); } true true The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches. Using String find Method Returns the byte index of the first character of this string slice that matches the pattern. Returns None if the pattern doesn’t match. fn main() { let s = "Löwe"; if s.find('ö') != None { // Found println!("Found") } println!("{:?}", s.find('ö')); println!("{:?}", s.find('o')); } Found Some(1) None Using String chars Method You can use chars method to check if the string contains at least one lowercase alphabet character. fn main() { let s = "Löwe"; let b = s.chars().any(|c| c.eq(&'ö')); println!("{}", b); } true
Tomoki