cs61a:从入门到入土
Readme
一直想学,无奈,由于平时的作业很多,学业压力比较重,学了几节课就没有学了。
决定前面的就简单温习一下吧。不复习又不行,基本全忘记了,只记得自己学过。
炎热的夏天不想出门,适合在房间开着空调吃着西瓜玩着手机学习python。
希望这个暑假能肝完。
版本:CS 61A Fall 2021
Week 1
使用ok的方法
这是这门课的亮点之一,利用简单的命令行的知识来检测你写出来的程序是否正确,并且每一个case都会告诉你是什么应该输出什么而你输出了什么,从而判断正确与否。
(在此点名华大的oj,什么都不给,只告诉你AC或WA等等,改都不知道怎么改)
之前没学过git,估计用git更简单。
win+R,输入cmd
然后在命令行界面输入powshell
在powershell里用cd ~/Desktop/cs61a/…来进入相应的位置
然后粘贴题目提供的含ok语句即可
vscode可以和power shell交互,故可省去第一步
可以直接用git bash here进入相应的位置,然后粘贴ok语句即可
Functions
expressions
即表达式,具体讲解了表达式嵌套时应遵循一定的顺序
name
from math import pi
可自行定义一个function的名称,例如:
def square(x) return mul(x,x)
1
2
3
4
* ```python
def area()
return pi*radius*radius可通过更改radius的值来改变area的值
environment diagrams
to visualize the interpreter’s process
(个人认为就是把程序的进行过程列出来方便理解
defining functions
1 | def <name>(<formal parameters>): |
def这一行的后面一定不要忘了有冒号!
Week 2
Control
Print and None
我理解的是,print输出了一个数,但是返回None(即什么都不返回)
而return返回了这个数
Multiple Environments
指的是def的函数嵌套,应该从里向外展开
Some features
除法 “/“
2013/10
1
2
3 from operator import truediv,floordiv
>>>truediv(2013,10)
201.32013//10(舍去后面的数,非四舍五入)
1
2
3 from operator import truediv,floordiv
>>>floordiv(2013,10)
201
A%B=mod(A,B)
定义函数的时候可以给形参赋值,调用时可以不把已被赋值的参数写出来
Conditional Statements
类似于C++中的if语句,仅语法有所差别
关心的是Boolean语句的对或错,而不关注表达式本身
Iteration(迭代)
讲的是while循环
1 | while (condition): |
Higher-Order Functions
when designing functions
- give each function exactly one job
- do not repeat yourself (DRY). implement a process just once,but execute it many times.
- define functions generally
可以用assert来检查输入的数据是否符合标准
格式:assert (A),(B)
1 | assert r>0,'A length must be positive.' |
即A语句为一个bool语句。如果判断为false,则程序报错并输出B语句
不要忘了pow函数!pow(k,3)即为求k的三次方
higher-order functions
A higher order function (HOF) is a function that manipulates other functions by taking in functions as arguments, returning a function, or both.
类似C++中函数之间的相互调用
- Express general methods of computation
- Remove repetition from programs
- Separate concerns among functions
lambda expressions
与def类似,但是lambda expressions不能包含statements
lambda的是变量
使用格式:
1 | square=lambda x:x*x |
与def的区别:
即def给了函数一个具体的名称,而lambda没有给,除非自己给它命名一个
conditional expressions
form:
evaluation rule:
- Evaluate the
expression. - If it’s a true value, the value of the whole expression is the value of the
- Otherwise, the value of the whole expression is the value of the
Environments for Higher-Order Functions
nested functions(嵌套)
1 | def make_adder(n): |
How to draw an environment dragram
function currying
即higher-order function
比如:
1 | def curry2(f): |
1 | >>>curry2=lambda f:lambda x:lambda y:f(x,y) |
currying:Transforming a multi-argument function into a single-argument,higher-order function
Disc 01: Control,Environment Diagrams
罗列几个与C++不同的注意点
- Boolean Operators中不要像C++一样使用&&和||,而是要使用and,or,not
- 不要使用i++,用i=i+1或i+=1
- python打印是自动换行的
Week 3
Design
Naming
- 不注重正确性而注重可读性。应该包含变量的meaning or purpose
- 长的name通常易读,如:average_age=average(age, students)
- 短的name通常是大家常用的符号。如:n, k, i for integers; x, y, z for real numbers and f, g, h for functions
Week 4
Recursion
Definition:the body of the function calls itself,either directly or indirectly
Anatomy:
- Base case:Evaluated without a recursive call(the smallest subproblem)
- Recursive case:Evaluated with a recursive call(breaking down the problem further)
- Conditional atatement:to decide of it’s a base case
Recursion and Iteration
Recursion:updates via assignment become…
如digit_sum=digit_sum+last
Iteration:…arguments to a recursive call
如return sum_digits_rec(n,digit_sum+last)
Tree Recursion
Tree-shaped processes arise whenever executing the body of a recursive function makes more than one call to that function
Week 5
Containers
Lists
1 | >>>digits=[1,8,2,8] |
The number of elements:len(digits)
An element selected by its index:digits[3] or getitem(digits,3)
Concatenation and repetition:[2,7]+digits*2 or add([2,7],mul(digits,2)) =[2,7,1,8,2,8,1,8,2,8]
Nested lists:pairs=[[10,20],[30,40]]
pairs[1]=[30,40] pairs[1][0]=30
1 | >>>1 in digits |
For Statements
for循环与lists很搭
1 | for <name> in <expression>: |
如:
1 | pairs=[[1,2],[2,2],[3,2],[4,4]] |
Ranges
A range is a sequence of consecutive integers.
如range(-2,2)表示-2,-1,0,1;range(4)=range(0,4)表示0,1,2,3
Length:ending value - starting value
Element selection:starting value + index
1 | >>>list(range(-2,2)) |
1 | def cheer(): |
List Comprehentions
构建list的方式:
1 | >>>odds=[1,3,5,7,9] |
Strings
“” or ‘’均可
“””…”””注释
Length and element selection are similar to all sequences.
However, the “in” and “not in” operators match substrings.
1 | >>>city='Berkeley' |
Sequences
Slicing
1 | >>>odds=[3,5,7,9,11] |
Slicing creates new values.
String is like a list and the functions can use slicing. For example:
1 | def reverse(s): |
Processing Container Values
- sum(iterable[, start])–>value
(not strings
1 | >>>sum[2,3,4] |
max(iterable[, key=func])–>value
max(a, b, c, …[, key=func])–>value
all(iterable)–>bool
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
1 | >>>bool(0) |
Data Abstraction
类似C++中的类
Dictionaries
Dictionaries are collections of key-value pairs.
Dictionary keys do have two restrictions:
- A key of a dictionary cannot be a list or a dictionary.
- Two keys cannot be equal; There can be at most one value for a given key.
如
1 | >>>numerals= {'I': 1, 'V': 5,'X': 10} |
1 | >>>d={1:['first','second'],3:'third'} |
Dictionary Comprehensions
1 | {<key exp>:<value exp> for <name> in <iter exp> if <filter exp>} |
如:
1 | {x*x:x for x in [1,2,3,4,5] if x>2} == {9:3,16:4,25:5} |
Week 6
Trees
The Tree Abstraction
A tree has a root label and a list of branches.
Each branch is a tree.
- root: the node at the top of the tree
- label: the value in a node
- branches: a list of trees directly under the tree’s root
- leaf: a tree with zero branches
- node: any location within the tree (e.g., root node, leaf nodes, etc.)
- Depth: the distance of a node and the root
- Height: The depth of the lowest (furthest from the root) leaf.
1 | def tree(label,branches=[]): |
1 | >>>tree(1) |
补充:the difference from tree class and tree abstraction
- Tree constructor and selector functions Tree class Constructing a tree To construct a tree given a label
and a list ofbranches
, we calltree(label, branches)
To construct a tree object given a label
and a list ofbranches
, we callTree(label, branches)
(which calls theTree.__init__
method).Label and branches To get the label or branches of a tree t
, we calllabel(t)
orbranches(t)
respectivelyTo get the label or branches of a tree t
, we access the instance attributest.label
ort.branches
respectively.Mutability The functional tree data abstraction is immutable because we cannot assign values to call expressions The label
andbranches
attributes of aTree
instance can be reassigned, mutating the tree.Checking if a tree is a leaf To check whether a tree t
is a leaf, we call the convenience functionis_leaf(t)
To check whether a tree t
is a leaf, we call the bound methodt.is_leaf()
. This method can only be called onTree
objects.
Tree Progressing
Creating Trees:A function that creats a tree from another tree is typically alse recursive.
1 | def increment_leaves(t): |
Example-Printing Trees
1 | def print_tree(t): |
优化后能显示树的结构:
1 | def print_tree(t,indent=0): |
Example-Summing Paths
1 | def print_sums(t,so_far): |
Example-Counting Paths
1 | def count_paths(t,total): |
Mutability
Mutation Operations
对list的操作:
移出元素:.pop()和.remove(…)。前者弹出最后一个元素,后者可移出任意一个元素
增加元素:.append(…)和.extend(…)
替换元素:采取切片赋值的方法
1 | >>>suits=['coin','string','myriad'] |
Some Objects Can CHange
The same object can change in value throughout the course of computation.
All names that refer to the same object are affected by a mutation.
Only objects of mutable types can change: lists & dictionaries.
Tuples(元组)
immutable sequences, meanings of these cannot be changed.
使用(),其余与list基本类似
1 | >>>(3,4,5,6) |
A dictionary cannot use a list as its index but can use a tuple. However, a tuple used as a index cannot include a list. For example:
1 | >>>{(1,2):3} |
An immutable sequence may still change if it contains a mutable value as an element. For example:
1 | >>>s=([1,2],3) |
Mutation
Sameness and Change
- A compound data object has an “identity” in addition to the pieces of which it is composed
- A list is still “the same” list even if we change its contents
- Conversely, we could have two lists that happen to have the same contents, but are different
Identity Operators
- Identity:
is 用 - evaluates to True if both
and evaluate to the same object
- evaluates to True if both
- Equality:
== - evaluates to True if both
and evaluate to equal values
- evaluates to True if both
Identical objects are always equal values.
Syntax
Data Abstraction for Syntax
用树的观念来分析英语语法
1 | def phrase(tag, branches): |
Parsing
Some files are plain text and can be read into Python as either.
- open(…) . read():One string containing the whole contents of the file
- open(…) . readlines():A list of strings, each containing one line
Useful string methods for processing the contents of a file.
.strip():returns a string without whitespace (spaces, tabs, etc.) on the ends
1
2>>>'hello '.strip()
'hello'.split():returns a list of strings that were separated by whitespace
1
2>>>'hi there'.split()
['hi','there'].replace(a,b):returns a string with all instances of string a replaces by string b
1
2>>>'2+2'.replace('+',' + ')
'2 + 2'
From lines to tokens:
use open(…).readlines():
1 | ['(ROOT (S (NP (NN this)) (VP (COP is) (NP (DT a) (NN book))) (. ?)))\n' |
to
1 | [['(', 'ROOT', '(', 'S', '(', 'NP', '(', 'NN', 'this', ')', ')', |
read_sentences takes care of this:
1 | lines = open('suppes.parsed').readlines() |
Generating Language
language models:A statistical(or probabilistic) language model describes how likely some text would be.
Sampling from a statistical language model uses what description to generate language.
1 | 详见https://code.cs61a.org/ |
Week 7
Iterators
Iterators
A container can provide an iterator that provides access to its elements in some order.
- iter(iterable):Return an iterator over the elements of an iterable value
- next(iterator):Return the next element in an iterator
1 | >>>s=[[1,2],3,4,5] |
There are also some built-in functions that take in iterables and return useful results:
map(f, iterable)
- Creates an iterator overf(x)
forx
initerable
. In some cases, computing a list of the values in this iterable will give us the same result as [func(x)
forx
initerable
]. However, it’s important to keep in mind that iterators can potentially have infinite values because they are evaluated lazily, while lists cannot have infinite elements.filter(f, iterable)
- Creates an iterator overx
for eachx
initerable
iff(x)
zip(iterables*)
- Creates an iterator over co-indexed tuples with elements from each of theiterables
reversed(iterable)
- Creates an iterator over all the elements in the input iterable in reverse orderlist(iterable)
- Creates a list containing all the elements in the inputiterable
tuple(iterable)
- Creates a tuple containing all the elements in the inputiterable
sorted(iterable)
- Creates a sorted list containing all the elements in the inputiterable
reduce(f, iterable)
- Must be imported withfunctools
. Apply function of two argumentsf
cumulatively to the items ofiterable
, from left to right, so as to reduce the sequence to a single value.
Dictionary Iteration
An iterable value is any value that can be passed to iter to produce an iterator.
An iterator is returned from iter and can be passed to next; all iterators are mutable.
A dictionary, its keys, its values, and its items are all iterable values.
For example:
1 | >>>d={'one':1, 'two':2, 'three':3} |
ATTENTION:dictionary cannot change size during iteration. For example:
1 | >>>d={'one':1,'two':2} |
Zip
The built-in zip function returns an iterator over co-indexed tuples.
If one iterable is longer than the other, zip only iterates over matches and skips extras
More than two iterables can be passed to zip
1 | >>>list(zip([1,2],[3,4])) |
Generators
Generator Function
- A generator function is a function that yields values instead of returning them.
- A normal function returns once; a generator function can yield multiple times
- A generator is an iterator created automatically by calling a generator function
- When a generator function is called, it returns a generator that iterates over its yields
1 | >>>def plus_minus(x): |
1 | for x in coutdown(k-1) |
A yield from statement can be used to yield the values from an iterable one at a time.
A Return Statement Within a Generator Function
Upon executing a return statement, a generator function exits and cannot yield more values.
What’s more, providing a value to be returned is allowed, but this value is not yielded.
For example:
1 | def f(x): |
It’s possible to access the returned value:
1 | def h(x): |
Objects
开始面向对象了…
Object-Oriented Programming
- class: a template for creating objects
- instance: a single object created from a class
- instance variable: a data attribute of an object, specific to an instance
- class variable: a data attribute of an object, shared by all instances of a class
- method: a bound function that may be called on all instances of a class
Class Statements
格式:
1 | class<name>: |
Every call to a class creates a new instance(对象). There’re many instances but only one class.
Binding an object to a new name using assignment does not create a new object. It just gives a new name to the object. For example:
1 | >>>c=a |
Methods
Methods are defined in the suite of a class statement.
The def statements create function objects as always, but their names are bound as attributes of the class.
All invoked methods have access to the object via the self parameter, and so they can all access and manipulate the object’s state. For example:
1 | class Account: |
Class Methods(*)
Now we’ll try out another feature of Python classes: class methods. A method can be turned into a class method by adding the classmethod decorator. Then, instead of receiving the instance as the first argument (self
), the method will receive the class itself (cls
).
Class methods are commonly used to create “factory methods”: methods whose job is to construct and return a new instance of the class.
For example, we can add a robo_factory
class method to our Dog
class that makes robo-dogs:
1 | class Dog(Pet): |
Then a call to Dog.robo_factory('Sally')
would return a new Dog
instance with the name “RoboDog” and owner “Sally”.
Attributes
Attributes are all public.
Accessing Attributes:
- getattr(object,’…’):
1 | >>>getattr(tom_account,'balance') |
getattr and dot expressions look up a name in the same way.
- hasattr(object,’…’): 用来判断对象是否包含对应的属性
1 | >>>hasattr(tom_account,'deposit') |
Class attributes are “shared” across all instances of a class because they are attributes of the class, not the instance. For example:
1 | class Account: |
- Instance Attribute Assignment: tom_account.interest=0.08
- adds or modifies the attribute named “interest” of tom_account(仅改变这个对象中这个属性的值
- Class Attribute Assignment: Account.interest=0.04
- 改变整个class中这个属性的值
Week 8
Inheritance
Inheritance is a method for relating classes together.
A common use:Two similar classes differ in their degree of specialization.
格式:
1 | class <name>(<base class>): #单继承 |
For example:
1 | class CheckingAccount(Account): #CheckingAccount继承了Account |
The new subclass shares attributes with its base class.
Using inheritance, we implement a subclass by specifying its differences from the base class.
Looking Up Attribute Names on Classes
To look up a name in a class:
- if it names an attribute in the class, return the attribute value.
- Otherwise, look up the name in the base class, if there is one.
即如果自己定义了新属性按新属性来,没有新定义的话就找继承的class看有没有相应的属性
类的继承,调用父类的属性和方法参考:
Representation
String Representation
- dir(object):returns a list of all the attributes on an object
- _str_():returns a human readable string representation of an object
- _repr_():returns a string that would evaluate to an object with the same values
f string
String interpolation involves evaluating a string literal that contains expressions.
Using string concatenation:
1
2
3
4
5>>>from math import pi
>>>'pi starts with'+str(pi)+'...'
'pi starts with 3.141592653589793...'
>>>print('pi starts with'+str(pi)+'...')
pi starts with 3.141592653589793...Using string interpolation:
1
2
3
4>>>f'pi starts with (pi)...'
'pi starts with 3.141592653589793...'
>>>print(f'pi starts with (pi)...')
pi starts with 3.141592653589793...
**{}**中的值会被算出来
Polymorphic Functions(多态)
Polymorphic function:A function that applies to many (poly) different forms (morph) of data
For example:str and repr are both polymorphic.
repr 和_repr_的区别:repr invokes a zero-argument method _repr_ on its argument
…to be continued
Special Method Names
Name | Behavior |
---|---|
_init_ | Method invoked automatically when an object is constructed |
_repr_ | Method invoked to display an object as a Python expression |
_str_ | Methof invoked to stringify an object |
_add_ | Method invoked to add one object to another |
_bool_ | Method invoked to convert an object to True or False |
_float_ | Method invoked to convert an object to a float(real number) |
For example:
1 | >>>one+two |
……
就是一些有特殊功能的函数前后会各有两个下划线
Recursive Objects
Linked Lists(链表)
Linked List Class
A linked list is either empty or a first value and the rest of the linked list.
每个link分为first和rest两部分
linked list class: attributes are passed to _init_
1 | class Link: |
Linked Lists Can Change
Attribute assignment statements can change first and rest attributes of a Link.
The rest of a linked list can contain the linked list as a sub-list
如果想在链表下标0处插入一个元素,可以直接将新元素的下一位指向原先的链表头
Week 9
Efficiency
开始考虑程序的运行时间了…
Memoization
1 | def memo(f): |
本节用的是斐不那几树的例子:
即如果这一个分支在前面已经出现过了,那么在这一步中就会跳过,这样大大地减少了迭代的次数
Orders of growth
Constant growth. Increasing n doesn’t affect time.
Decomposition(分解
也就是将各个功能分开撰写与调试
Week 11
似乎到这里换了种语言——scheme
Scheme
Scheme 编程语言是一种Lisp方言
是第一个引入“干净宏”的编程语言
Scheme programs consist of expressions, whichcan be:
- Primitive expressions:2, 3.3, true, +,quotinent…
- Combinations:(quotient 10 2), (not true), …
For example:
1 | scm> (quotient 10 2) |
Special forms
A combination that is not a call expression is a special form:
If expression: (if
) And and or: (and
… ) (or … ) Binding symbols(定义常量):(define
) New procedures(定义函数,symbol是函数名,formal parameters是变量名):
(define (
) )
For example:
1 | > (define pi 3.14) |
- Lambda expressions: (lambda (
) )
Two equivalent expressions:
1 | (define (plus4 x) (+ x 4)) |
An operator can be a call expression too:
1 | ((lambda (s y z) (+ x y (square z))) 1 2 3) |
More special forms
Cond
The cond special form that behaves like if-elif-else statements in Python
1 | (cond ((<条件>) (<expressions>)) |
Begin
The begin special form combines multiple expressions into expression
1 | ...begin(<expression1>)(<expression2>) |
Let
The let special form binds symbols to values temporarily; just for one expression
Lists
- cons:Two-argument procedure that creates a linked list
- car:Procedure that returns the first element of a list
- cdr:Procedure that returns the rest of a list
- nil:The empty list
Important! Scheme lists are written in parentheses with elements separated by spaces
For example:
1 | > (cons 1 (cons 2 nil)) |
Symbolic Programming
Symbols normally refer to values; how do we refer to symbols?
1 | >(define a 1) |
Quotation is used to refer to symbols directly in Lisp
‘a == (quote a)
1 | >(list 'a 'b) |
Quotation can also be applied to combinations to form lists
1 | >'(a b c) |
Exceptions
Quasiquotation
Two ways to quote an expression
Quote: ‘(a b) => (a b)
Quasiquote: `(a b) => (a b)
They are different because parts of a quasiquoted expression can be unquoted with
(define b 4)
Quote: ‘(a, (+ b 1)) => (a (unquote (+ b 1)))
Quasiquote: `(a, (+ b 1)) => (a 5)
Example:While Statements
1 | #python |
1 | #scheme |
Exceptions
Assert Statements
1 | assert <expression>, <string> |
Assertions are disigned to be used liberally. They can be ignored to increase efficiency by running Python with the “-0” flag. “0” stands for optimized.
Raise Statements
Exceptions are raised with a raise statement.
1 | raise <expression> |
E.g. raise TypeError(‘Bad argument!’)
- TypeError——A function was passed the wrong number/type of argument
- NameError——A name wasn’t found
- KeyError——A key wasn’t found in a dictionary
- RuntimeError——Catch-all for troubles during interpretation
Try Statements
是在面临上述exceptions时
Try statements handle exceptions
1 | try: |
Executing rule:
The
If, during the course of executing the
Then the
For example:
1 | >>>try: |
Multiple try statements: Control jumpps to the except suite of the most recent try statement that handles that type of exception.
Calculator
The Pair class represents Scheme pairs and lists. A list is a pair whose second element is either a list or nil
Scheme expressions are represented as Scheme lists!
Calculator Semantics
The value of a calculator expression is defined recursively.
Primitive: A number evaluates to itself
Call: A call expression evaluates to its argument values combined by an operator
week 12
Tail Calls
A procedure call taht has not yet returned is active. Some procedure calls are tail calls. A Scheme interpreter should support an unbounded number of active tail calls using only a constant amount of space.
A tail call is a call expression in a tail context:
- The last body sub-expression in a lambda expression
- Sub-expressions 2&3 in a tail context if expression
- All non-predicate sub-expressions in a tail context cond
- The last sub-expression in a tail context and or or
- The last sub-expression in a tail context begin
Tail Recursion:尾递归
在尾递归中只有前进的过程,而在普通递归中还有压栈、栈的回退、栈空等过程。
【1】在尾递归中,其实只有前进的过程,也就是顺藤摸瓜(瓜就是返回结果)。摸到瓜结束。
【2】在普通递归中,我们摸到了瓜(这个瓜在这里指的是递归的base case),你还得记住你怎了顺的藤(将中间过程压栈),然后在把瓜顺着藤捣腾回去(栈的回退),直到到了最初的起点(栈空)。然后返回。
Regular Expressions
Types of Programming
Imperative programming(命令式编程):Describe what you want a computer to do
Often involves mutation for the purpose of computing a result
Computational efficiency is often determined by the details of the program
E.g. oop is a useful way of organizing imperative programs.
Declarative programming(声明式编程):Describe the result you want a computer to produce
Often abstracts away the details of how memory is changing during computation
Computational efficiency is often determined by the interpreter or language
E.g. functional programming(函数式编程) describes a result using function composition
General-purpose languages:Designed to describe any computation
Python, Scheme, Javascript, Java, C, C++, etc
Languages differ in the programming styles that they promote
Language features make some languages more suitable to certain applications
Domain-specific languages:Designed to solve particular classes of problems
SQL, HTML, CSS, regular expressions, etc
Often declarative in character:the language describes what to compute/create, not how
Often embedded into general-purpose languages
Character classes
Class | Description |
---|---|
[abc] |
Matches a, b, or c |
[a-z] |
Matches any character between a and z |
[^A-Z] |
Matches any character that is not between A and Z. |
\w |
Matches any “word” character. Equivalent to [A-Za-z0-9_] |
\d |
Matches any digit. Equivalent to [0-9] . |
[0-9] |
Matches a single digit in the range 0 - 9. Equivalent to \d |
\s |
Matches any whitespace character (spaces, tabs, line breaks). |
. |
Matches any character besides new line. |
Week 13
Backus-Naur Form
详见百度百科或wiki
尖括号( < > )内包含的为必选项。
方括号( [ ] )内包含的为可选项。
大括号( { } )内包含的为可重复0至无数次的项。
竖线( | )表示在其左右两边任选一项,相当于”OR”的意思。
::= 是“被定义为”的意思
SQL
Databases
数据库
In declarative languages such as SQL &Prolog:
- A “program” is a description of the desired result
- The interpreter figures out how to generate the result
In imperative languages such as Python & Scheme:
- A “program” is a description of computational processes
- The interpreter carries out execution/evaluation rules
1 | create table cities as |
Structured Query Language(SQL)
- A select statement creates a new table, either from scratch or by projecting a table
- A create table statement gives a global name to a table
- Lots of other statements exist:analyze, delete, explain, insert, replace, update, etc
- Most of the important action is in the select statement
- The code for executing select statements fits on a single sheet of paper
1 | select [expression] as [name], [expression] as [name] |
The result of a select statement is displayed to the user, but not stored
A create table statement gives the result a name
For example:
1 | create table parents as |
projecting tables
Tables
Creating tables with SELECT
1 | create table top_music_videos as |
Creating tables with UNION
1 | create table music_movies as |
2-step table creation
1 | createtable musical_movies (title text, releas_year interger); |
Week14
Aggregation
Aggregate functions
SELECT [columns] FROM [table] WHERE [expression];
SELECT MAX(columns) FROM [table];
For example:
1 | select body, max(mean_radius) from solar_system_objects; |
Group
Grouping rows
rows in a table can be grouped using group by
SELECT [columns] FROM [table] GROUP BY [expression];
For example:
1 | select legs, max(weight) from animals group by legs; |
Filtering groups
using having clause
SELECT [columns] FROM [table] GROUP BY [expression] HAVING [expression];
For example:
1 | select weight/legs, count(*) from animals group by weight/legs having count(*) >1; |
Week 15
Conclusion
I love John DeNero!
don’t compare
In real life how you compare how you compare to somebody else doesn’t matter very much at all
what does matter is what you’re capable of what you do how you choose to spend your time and what impact you have on the world
and so it turns out your self-worth has nothing to do with what other people achieve and has everything to do with what you achieve
完结撒花~~~