06_advanced_programming.ipynb
- Lecture 6: Advanced Programming
- Outline
- Recursive Functions
- Stackoverflow (Types of error III)
- Multi-dimensional Arrays
- Matrix Addition and (Scalar) Multiplication
- Addition:
- Multiplication
- Scalar multiplication
- Dictonaries
- The `keys` and `values` functions
- Example: A dictionary as a collection of counters
- Summary: Looking Back and Looking Forward
- File 文件
- Edit 编辑
- View 看法
- Run
- Kernel 核心
- Settings 设置
- Help 帮助
Introduction to Programming for Business Analytics
业务分析编程简介 ¶
业务分析编程简介
Lecture 6: Advanced Programming¶
第 6 讲:高级编程 ¶
Outline¶ 大纲 ¶
- Recursive Functions (Recursions)
递归函数(递归) - Stackoverflow (Types of error III)
Stackoverflow(错误类型 III) - Multi-dimensional Arrays and Matrix Operations
多维数组和矩阵运算 - Dictionaries 词典
Recursive Functions¶ 递归函数 ¶
- A recursive function is a function that calls itself during its execution.
递归函数是在执行过程中调用自身的函数。 - It may not be obvious why that is a good thing, but it turns out to be one of the most powerful things a program can do.
为什么这是一件好事可能并不明显,但事实证明这是程序可以做的最强大的事情之一。
Consider the product of all positive integers less than or equal to n
, known as factorial, which is denoted by
考虑所有小于或等于 n
的正整数的乘积,称为阶乘,用
Note that the factorial of
can also be written as the product of with the next smaller factorial
请注意, 的阶乘也可以写为 与下一个较小阶乘 的乘积This definition says that the factorial of
is , and the factorial of any other value, , is multiplied by the factorial of . So
此定义表示 的阶乘为 ,任何其他值的阶乘 为 乘以 的阶乘。所以 .
Putting it all together .
把它们放在一起 。
If you can write a recursive definition of something, you can write a Julia program to evaluate it.
如果您可以编写某事物的递归定义,您就可以编写 Julia 程序来评估它。
Note: Julia has a built-in function called factorial
that calculates the factorial of non-negative integer numbers. To avoid naming conflicts, we will use the name my_factorial
for our user-defined function.
注意:Julia 有一个名为 factorial
的内置函数,用于计算非负整数的阶乘。为了避免命名冲突,我们将使用名称 my_factorial
作为用户定义的函数。
my_factorial (generic function with 1 method)
6
If we call the function my_factorial
with the value 3
, the flow of execution is as follows:
如果我们使用值 3
调用函数 my_factorial
,执行流程如下:
n=3
n=3
n=2
n=2
n=1
n=1
n=0
1
without making any more recursive calls.
n=0
1
,而不再进行任何递归调用。
return 1
n=1
, and the result 1*1=1
is returned.
return 1
n=1
相乘,返回结果 1*1=1
。
return 1
n=2
, and the result 1*2=2
is returned.
return 1
n=2
相乘,返回结果 1*2=2
。
return 2
n=3
, and the result 2*3=6
becomes the returned value of the function.
return 2
n=3
,结果 2*3=6
成为函数的返回值。
The key here is to note that this recursive procedure STOPS when we reach
这里的关键是要注意,当我们到达
- The expression where the recursive procedure reaches a termination point is called an anchor.
递归过程到达终止点的表达式称为锚点。 - Every recursive function MUST have an anchor.
每个递归函数都必须有一个锚点。
Adding print statements can help us to understand what is happening behind the scenes.
添加打印语句可以帮助我们了解幕后发生的事情。
my_visual_factorial (generic function with 1 method)
factorial 3 factorial 2 factorial 1 factorial 0 returning 1 returning 1 returning 2 returning 6
6
Stackoverflow (Types of error III)¶
Stackoverflow(错误类型 III) ¶
- Stackoverflow is an error that occurs in computer programs, typically due to recursive function calls.
Stackoverflow 是计算机程序中发生的错误,通常是由于递归函数调用造成的。 - Each function call is added to a data structure known as the call stack.
每个函数调用都添加到称为调用堆栈的数据结构中。 - When functions call each other recursively without a proper termination condition, the call stack grows excessively, leading to a stack overflow.
当函数在没有适当终止条件的情况下递归地相互调用时,调用堆栈会过度增长,从而导致堆栈溢出。 - A Stackoverflow can result in program termination or a crash because the system's memory allocated for the call stack is exhausted, preventing further function calls, and indicating a programming error that needs to be addressed.
Stackoverflow 可能会导致程序终止或崩溃,因为分配给调用堆栈的系统内存已耗尽,从而阻止进一步的函数调用,并指示需要解决的编程错误。
Example: 例子:
recursive_function (generic function with 1 method)
StackOverflowError: Stacktrace: [1] recursive_function(x::Int64) (repeats 79984 times) @ Main c:\Users\Sebastian Feller\Documents\03_Uni\02_Hiwi_DPO\01_Lecture_Reworks\06_advanced_programming.ipynb:5
Multi-dimensional Arrays¶
多维数组 ¶
Recall that we can define a one-dimensional array (vector) using square brackets and commas to separate the elements within the array.
回想一下,我们可以使用方括号和逗号来定义一维数组(向量)来分隔数组中的元素。
[1, 2, 3
We can also define two-dimensional arrays using space to separate elements in a row and semicolons (;
) to separate rows.
我们还可以定义二维数组,使用空格分隔行中的元素,使用分号 ( ;
) 分隔行。
2×3 Matrix{Int64}: 1 2 3 4 5 6
The built-in function size
returns a tuple containing the dimensions of the array given as input.
内置函数 size
返回一个元组,其中包含作为输入给出的数组的维度。
(2, 3)
2
3
- The syntax for accessing elements of a multi-dimensional array is similar to that of accessing one-dimensional arrays. It uses integer values enclosed between square brackets.
访问多维数组元素的语法与访问一维数组的语法类似。它使用方括号括起来的整数值。 - Main difference is, because they contain multiple dimensions, each dimension has its index and those indicies are separated using commas.
主要区别在于,因为它们包含多个维度,所以每个维度都有其索引,并且这些索引使用逗号分隔。
2×3 Matrix{Int64}: 1 2 3 4 5 6
1
2
4
6
- Slicing can also be done in a similar manner:
切片也可以用类似的方式完成:
2×3 Matrix{Int64}: 1 2 3 4 5 6
2-element Vector{Int64}: 1 2
2-element Vector{Int64}: 5 6
2-element Vector{Int64}: 2 5
We can actually obtain different slices by specifying the different parameters of the range (start:step:stop
) as we discussed in Lecture 3.
正如我们在第 3 讲中讨论的那样,我们实际上可以通过指定范围的不同参数 ( start:step:stop
) 来获得不同的切片。
The following example returns a slice, from row 1, containing only the elements that correspond odd indicies, in reverse order.
以下示例从第 1 行返回一个切片,其中仅包含与奇数索引相对应的元素(按相反顺序)。
2×5 Matrix{Int64}: 1 2 3 4 5 6 7 8 9 10
3-element Vector{Int64}: 5 3 1
3-element Vector{Int64}: 5 3 1
- Typing the range operator
:
without specifiying any of parameters (i.e.,start
,step
, andstop
) selects the whole corresponding dimension.
键入范围运算符:
而不指定任何参数(即start
、step
和stop
)会选择整个相应的维度。
5-element Vector{Int64}: 1 2 3 4 5
2-element Vector{Int64}: 2 7
Matrix Addition and (Scalar) Multiplication¶
矩阵加法和(标量)乘法 ¶
In Julia, multi-dimensional arrays support native implementations for matrix addition and (scalar) multiplication.
在 Julia 中,多维数组支持矩阵加法和(标量)乘法的本机实现。
Consider the following two matrices.
考虑以下两个矩阵。
Addition:¶ 添加: ¶
- The sum
is defined if and only if and have the same number of columns and the same number of rows.
当且仅当 和 具有相同的列数和相同的行数时,才定义总和 。 - The sum
is calculated entrywise.
总和 按条目计算。
In Julia, this is directly available using the +
operator.
在 Julia 中,可以使用 +
运算符直接使用。
2×2 Matrix{Int64}: 9 12 11 5
Multiplication¶ 乘法 ¶
- The multiplication
is defined if and only if the number of columns in is the same as the number of rows in .
当且仅当 中的列数与 中的行数相同时,才定义乘法 。 - The multiplication
is calculated
计算乘法
2×2 Matrix{Int64}: 22 18 39 44
- To multiply the matrices
and element-wise, we can use the dot operator (.
) as follows.
要将矩阵 和 按元素相乘,我们可以使用点运算符 (.
),如下所示。
2×2 Matrix{Int64}: 8 20 28 4
Scalar multiplication¶ 标量乘法 ¶
The product
数字
Suppose that
假设
In Julia, this is directly available using the *
operator.
在 Julia 中,可以使用 *
运算符直接使用。
2×2 Matrix{Int64}: 2 4 8 2
Dictonaries¶ 字典 ¶
- A dictionary is like an array, but more general: In an array, indices have to be integers, but in a dictionary they can be (almost) any type.
字典就像数组,但更一般:在数组中,索引必须是整数,但在字典中它们可以是(几乎)任何类型。 - Dictionary contains collection of indices called keys and collection of values.
字典包含称为键的索引集合和值集合。- Each key is associated with single value.
每个键都与单个值相关联。 - The association of every key and value is called key-value pair.
每个键和值的关联称为键值对。
- Each key is associated with single value.
Example: We are going to define a dictionary (called eng2de
) that maps from English to German words, so keys and values are all strings.
示例:我们将定义一个从英语单词映射到德语单词的字典(称为 eng2de
),因此键和值都是字符串。
- To define a dictonary we use a function called
Dict
.
为了定义字典,我们使用一个名为Dict
的函数。 - The function
Dict
called without any arguments to it creates new dictionary with no items.
不带任何参数调用的函数Dict
创建没有项目的新字典。
Dict{Any, Any}()
To add items to a dictionary, we use square brackets []
.
要将项目添加到字典中,我们使用方括号 []
。
"eins"
- If we print the
eng2de
dictionary, it will show a key-value pair with an arrow=>
in between.
如果我们打印eng2de
字典,它将显示一个键值对,其间有一个箭头=>
。
Dict{Any, Any}("one" => "eins")
- We can also initialize a dictonary with multiple key-value pairs.
我们还可以用多个键值对初始化一个字典。
Dict{String, String} with 3 entries: "two" => "zwei" "one" => "eins" "three" => "drei"
If we print the eng2de
dictionary, it will show three key-value pairs with an arrow =>
in between each pair.
如果我们打印 eng2de
字典,它将显示三个键值对,每对之间有一个箭头 =>
。
Dict("two" => "zwei", "one" => "eins", "three" => "drei")
The key "two"
always maps to value "zwei"
and the order of items does not matter.
键 "two"
始终映射到值 "zwei"
并且项目的顺序并不重要。
"zwei"
If a key is not in dictionary (e.g., "four"
), we get an exception.
如果某个键不在字典中(例如 "four"
),我们会得到一个异常。
"vier"
The keys
and values
functions¶
keys
和 values
函数 ¶
- The function
keys
returns a collection of elements with the keys of the dictionary.
函数keys
返回带有字典键的元素集合。
KeySet for a Dict{String, String} with 4 entries. Keys: "two" "four" "one" "three"
- The function
values
returns a collection of elements with the values of the dictionary.
函数values
返回具有字典值的元素集合。
ValueIterator for a Dict{String, String} with 4 entries. Values: "zwei" "vier" "eins" "drei"
Example: A dictionary as a collection of counters¶
示例:作为计数器集合的字典 ¶
Define a function called histogram
that takes a string value called word
as a parameter and returns a dictonary that shows the count of how many each letter appears. The returned dictonary should have the unique letters in word
as keys and the number of time each corresponding letter appeared as values. Test your function using the word "banana"
.
定义一个名为 histogram
的函数,该函数采用名为 word
的字符串值作为参数,并返回一个字典,该字典显示每个字母出现的次数。返回的字典应将 word
中的唯一字母作为键,并将每个相应字母出现的次数作为值。使用单词 "banana"
测试您的函数。
histogram (generic function with 1 method)
Dict{Any, Any} with 3 entries: 'n' => 2 'a' => 3 'b' => 1
Summary: Looking Back and Looking Forward¶
摘要:回顾与展望 ¶
Looking Back: 回头看:
- A recursive function is a function that calls itself during its execution.
递归函数是在执行过程中调用自身的函数。 - Stack overflow is a program crash due to too many function calls.
堆栈溢出是由于函数调用过多而导致的程序崩溃。 - Two-dimensional arrays are defined using square brackets, with spaces separating elements in a row and semicolons (
;
) separating columns.
二维数组使用方括号定义,用空格分隔行中的元素,用分号 (;
) 分隔列。 - Julia Multi-dimensional arrays support native implementations of matrix addition and (scalar) multiplication.
Julia 多维数组支持矩阵加法和(标量)乘法的本机实现。 - A dictionary is like an array, but more general: In an array, indices have to be integers, but in a dictionary they can be (almost) any type.
字典就像数组,但更一般:在数组中,索引必须是整数,但在字典中它们可以是(几乎)任何类型。
Looking Forward: 期待:
- Julia libraries and moduls: General Concept of a Software Library, Concept of Julia Modules, The Base and Standard Library, Installation and Removing Julia Packages, Julia Packages Example
Julia 库和模块:软件库的一般概念、Julia 模块的概念、基础和标准库、安装和删除 Julia 包、Julia 包示例