0%

Go - Basic Syntax

Tokens in Go

A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −

1
fmt.Println("Hello, World!")

The individual tokens are −

1
2
3
4
5
6
fmt
.
Println
(
"Hello, World!"
)

Identifiers

An identifier in go can only start with characters or _, and it is a combination of characters, numbers and underscores. For example, abc, _, _123, a123.

Keywords

There are 25 keywords in go:

1 2 3 4 5
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

And there are 37 reserved words in go:

Constants: true false iota nil

Types: int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex128 complex64 bool byte rune string error

Functions: make len cap new append copy close delete complex real imag panic recover

Variable

Format of declare a variable:

1
var variable_name variable_type

examples:

1
2
3
var name string
var age int
var isOk bool

or:

1
2
3
4
5
6
var (
a string
b int
c bool
d float32
)

Initiate a variale

Format:

1
var name type = value

examples:

1
2
3
4
var name string = "Q1mi"
var age int = 18

var name, age = "Q1mi", 18

or:

1
2
var name = "Q1mi"
var age = 18

and also we can use := operator to initiate a variable inside a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"fmt"
)
// declare global variable m
var m = 100

func main() {
n := 10
m := 200 // declare local variable m
fmt.Println(m, n)
}

If we want to ignore a value, we can use the anonymous variable with _ :

1
2
3
4
5
6
7
8
9
func foo() (int, string) {
return 10, "Q1mi"
}
func main() {
x, _ := foo()
_, y := foo()
fmt.Println("x=", x)
fmt.Println("y=", y)
}

Constant

Using keyword const to define a constant:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const pi = 3.14
const e = 2.7182

const (
pi = 3.14
e = 2.718
)

// n1 = n2 = n3 = 100
const (
n1 = 100
n2
n3
)

iota

1
2
3
4
5
6
const (
n1 = iota //0
n2 //1
n3 //2
n4 //3
)
1
2
3
4
5
6
const (
n1 = iota //0
n2 //1
_
n4 //3
)
1
2
3
4
5
6
7
const (
n1 = iota //0
n2 = 100 //100
n3 = iota //2
n4 //3
)
const n5 = iota //0
1
2
3
4
5
6
7
8
const (
_ = iota
KB = 1 << (10 * iota)
MB = 1 << (10 * iota)
GB = 1 << (10 * iota)
TB = 1 << (10 * iota)
PB = 1 << (10 * iota)
)
1
2
3
4
5
const (
a, b = iota + 1, iota + 2 //1,2
c, d //2,3
e, f //3,4
)

Download data set

Download data set from this [website](https://www.superdatascience.com/%E4%B8%8B%E8%BD%BD%E6%95%B0%E6%8D%AE%E9%9B%86/)

Importing the Libraries

Python data preprocessing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Data Preprocessing

# 1. Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 2. Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 3].values

# 3. Taking care of missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy = 'mean')
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])

# 4. Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
labelencoder_X = LabelEncoder()
X[:, 0] = labelencoder_X.fit_transform(X[:, 0])

# Virtual Coding for Country column
columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')
X = np.array(columnTransformer.fit_transform(X), dtype=np.str)

# Encoding the Dependent Variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)

# 5. Splitting the dataset into training set and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

# 6. Scaling features
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)

Basic BackTrack Frame

1
2
3
4
5
6
7
8
9
10
result = []
def backtrack(路径, 选择列表):
if 满足结束条件:
result.add(路径)
return

for 选择 in 选择列表:
做选择
backtrack(路径, 选择列表)
撤销选择

Full Permutation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
List<List<Integer>> res = new LinkedList<>();

/* 主函数,输入一组不重复的数字,返回它们的全排列 */
List<List<Integer>> permute(int[] nums) {
// 记录「路径」
LinkedList<Integer> track = new LinkedList<>();
backtrack(nums, track);
return res;
}

// 路径:记录在 track 中
// 选择列表:nums 中不存在于 track 的那些元素
// 结束条件:nums 中的元素全都在 track 中出现
void backtrack(int[] nums, LinkedList<Integer> track) {
// 触发结束条件
if (track.size() == nums.length) {
res.add(new LinkedList(track));
return;
}

for (int i = 0; i < nums.length; i++) {
// 排除不合法的选择
if (track.contains(nums[i]))
continue;
// 做选择
track.add(nums[i]);
// 进入下一层决策树
backtrack(nums, track);
// 取消选择
track.removeLast();
}
}

Queen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
vector<vector<string>> res;

/* 输入棋盘边长 n,返回所有合法的放置 */
vector<vector<string>> solveNQueens(int n) {
// '.' 表示空,'Q' 表示皇后,初始化空棋盘。
vector<string> board(n, string(n, '.'));
backtrack(board, 0);
return res;
}

// 路径:board 中小于 row 的那些行都已经成功放置了皇后
// 选择列表:第 row 行的所有列都是放置皇后的选择
// 结束条件:row 超过 board 的最后一行
void backtrack(vector<string>& board, int row) {
// 触发结束条件
if (row == board.size()) {
res.push_back(board);
return;
}

int n = board[row].size();
for (int col = 0; col < n; col++) {
// 排除不合法选择
if (!isValid(board, row, col))
continue;
// 做选择
board[row][col] = 'Q';
// 进入下一行决策
backtrack(board, row + 1);
// 撤销选择
board[row][col] = '.';
}
}

/* 是否可以在 board[row][col] 放置皇后? */
bool isValid(vector<string>& board, int row, int col) {
int n = board.size();
// 检查列是否有皇后互相冲突
for (int i = 0; i < n; i++) {
if (board[i][col] == 'Q')
return false;
}
// 检查右上方是否有皇后互相冲突
for (int i = row - 1, j = col + 1;
i >= 0 && j < n; i--, j++) {
if (board[i][j] == 'Q')
return false;
}
// 检查左上方是否有皇后互相冲突
for (int i = row - 1, j = col - 1;
i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q')
return false;
}
return true;
}

If we just want to find one answer, just return the result when reach the goal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 函数找到一个答案后就返回 true
bool backtrack(vector<string>& board, int row) {
// 触发结束条件
if (row == board.size()) {
res.push_back(board);
return true;
}
...
for (int col = 0; col < n; col++) {
...
board[row][col] = 'Q';

if (backtrack(board, row + 1))
return true;

board[row][col] = '.';
}

return false;
}

Data storage structure

Two basic structures of data strage are Array and LinkedList.
All other structures are developed from these two structures.

Action on Data structure

traversal

Array traversal:

1
2
3
4
5
void traverse(int[] arr) {
for (int i = 0; i < arr.length; i++) {
// iteration arr[i]
}
}

Single node linkedlist traversal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Single Node */
class ListNode {
int val;
ListNode next;
}

void traverse(ListNode head) {
for (ListNode p = head; p != null; p = p.next) {
// iteration p.val
}
}

void traverse(ListNode head) {
// recursion head.val
traverse(head.next)
}

Binary tree:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* Binary Tree */
class TreeNode {
int val;
TreeNode left, right;
}

void traverse(TreeNode root) {
// pre order
traverse(root.left)
// in order
traverse(root.right)
// post order
}

Tree:

1
2
3
4
5
6
7
8
9
10
/* N branch tree */
class TreeNode {
int val;
TreeNode[] children;
}

void traverse(TreeNode root) {
for (TreeNode child : root.children)
traverse(child)
}

As usual, HelloWorld

International practice :P

HelloWorld without Material Scaffold

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import 'package:flutter/material.dart';

class MyAppBar extends StatelessWidget{
MyAppBar({this.title});//
final Widget title;

@override
Widget build(BuildContext context){
return new Container(
height: 56.0,
padding: const EdgeInsets.symmetric(horizontal:8.0),
decoration: new BoxDecoration(
color:Colors.blue[400]
),
child: Row(
children: <Widget>[
new IconButton(
icon:new Icon(Icons.menu),
tooltip:'Navigation menu',
onPressed: (){
print('Click Menu');
},
),
new Expanded(
child:new Center(
child:title
)
),
new IconButton(
icon:Icon(Icons.search),
tooltip:'Search',
onPressed: (){
print('Click Search');
},
)
],
),
);
}
}

class MyScaffold extends StatelessWidget{
@override
Widget build(BuildContext context){
return Material(
child: new Column(
children:<Widget>[
new MyAppBar(
title:new Text(
'Hello World',
style:Theme.of(context).primaryTextTheme.title
),
),
new Expanded(
child:new Center(
child:Text('Hello World!!!')
)
)
]
),
);
}
}

void main(){
runApp(
new MaterialApp(
title:'My app',
home:new MyScaffold()
)
);
}

Installation and Configuration

Installation

For this part, please have a look at Flutter Official Website.

Configuration for web support

For now, to have the web support, we need to change to dev channel with the following command:

1
2
flutter channel dev
flutter upgrade

Then we need to enable the web support:

1
flutter config --enable-web

The last step is going to the project directory and apply those changes to our existing project:

1
2
3
cd <into project directory>
flutter create .
flutter run -d chrome --web-port=8080

If you don’t have any project, using

1
flutter create <project name>

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment