Composing Programs(SICP python版) chap1 笔记

《Composing Programs》(SICP python版) chap1 笔记

持续更新中

在学习 CS61A 2022fall的时候配着看的

文章目录

  • 《Composing Programs》(SICP python版) chap1 笔记
  • Chapter 1: Building Abstractions with Functions
    • 1.1 Getting Started
      • 1.1.1 Programming in Python
      • 1.1.2 Installing Python 3
        • pip安装过程(Ubuntu18.04)
      • 1.1.3 Interactive Sessions
      • 1.1.4 First Example
        • **Statements & Expressions**.
        • **Functions**.
          • 问题
        • **Objects**.
        • **Interpreters**.
      • 1.1.5 Errors
    • 1.2 Elements of Programming
    • 1.3 Defining New Functions
    • 1.4 Designing Functions
    • 1.5 Control
    • 1.6 Higher-Order Functions
    • 1.7 Recursive Functions
  • 相关资源

本书的preface

Welcome to Composing Programs, a free online introduction to programming and computer science.
In the tradition of SICP, this text focuses on methods for abstraction, programming paradigms, and techniques for managing the complexity of large programs. These concepts are illustrated primarily using the Python 3 programming language.
In addition to reading the chapters below, you can apply your knowledge to the programming projects that accompany the text and visualize program execution using the Online Python Tutor.
Instructors: If you are interested in adapting any of these materials for your courses, please fill out this short survey so that we can support your efforts.

Chapter 1: Building Abstractions with Functions

1.1 Getting Started

感觉这段话写的很棒

The high productivity of computer science is only possible because the discipline is built upon an elegant and powerful set of fundamental ideas.

计算机科学是建立在一套优雅而强有力的基本思想之上的,这使得它的高生产力成为可能。

All computing begins with representing information, specifying logic to process it, and designing abstractions that manage the complexity of that logic.

所有的计算都始于信息的表示,指定处理信息的逻辑,以及设计抽象概念来应对逻辑的复杂性。

Mastering these fundamentals will require us to understand precisely how computers interpret computer programs and carry out computational processes.

掌握这些基本原理需要我们准确地理解计算机如何解释程序并执行计算过程。

1.1.1 Programming in Python

  • Python is a widely used programming language that has recruited(吸收) enthusiasts from many professions.

  • The Python language itself is the product of a large volunteer community that prides itself on the diversity of its contributors. The language was conceived(构思) and first implemented(实现) by Guido van Rossum in the late 1980’s. The first chapter of his Python 3 Tutorial explains why Python is so popular, among the many languages available today.

  • Python excels(突出) as an instructional language( 作为一种教学语言非常出色) because, throughout its history, Python’s developers have emphasized the human interpretability (可解释性)of Python code, reinforced by the Zen of Python guiding principles of beauty, simplicity, and readability. Python is particularly appropriate for this text because its broad set of features support a variety of different programming styles, which we will explore. While there is no single way to program in Python, there are a set of conventions(一组约定) shared across the developer community that facilitate reading, understanding, and extending existing programs. Python’s combination of great flexibility and accessibility allows students to explore many programming paradigms(许多编程范式), and then apply their newly acquired knowledge to thousands of ongoing projects.

  • These notes maintain the spirit of SICP by introducing the features of Python in step with techniques for abstraction and a rigorous model of computation(严格的计算模型). In addition, these notes provide a practical introduction to Python programming, including some advanced language features and illustrative examples(说明性示例). Increasing your facility with Python should come naturally as you progress through the text.

1.1.2 Installing Python 3

  • 在lab0里面解决了python3的安装,但是当时没有装pip,这里来记录一下

pip安装过程(Ubuntu18.04)

  • 一开始以为自带了

    image-20221221193242133

  • 于是sudo apt install python-pip

    装好之后发现版本好低诶

    Composing Programs(SICP python版) chap1 笔记_第1张图片

    突然意识到可能是python2的pip

    Composing Programs(SICP python版) chap1 笔记_第2张图片

  • 于是查了一下Linux安装pip

    • 前往pip官网 https://pip.pypa.io/en/stable/installation/

      • 先是试了试那个ensurepip ,结果Ubuntu搞不了

        Composing Programs(SICP python版) chap1 笔记_第3张图片

    • 于是用下面那个get-pip.py

      wget https://bootstrap.pypa.io/get-pip.py
      

      习惯了win上直接python ,然鹅应该用python3
      image-20221221194001603

      查看了一下发现自己默认py3版本还是3.6

      先改成3.9

      ~$ sudo rm /usr/bin/python3
      ~$ sudo ln -s /usr/bin/python3.9 /usr/bin/python3
      
      
  • 以为可以python3 get-pip.py

    报了个错ModuleNotFoundError: No module named 'distutils.cmd'

    在askubuntu上面查了个解决方案

    sudo apt-get install python3-distutils
    sudo apt-get install python3-apt
    

    又来个错误ModuleNotFoundError: No module named 'apt_pkg'

    image-20221221194711938

    看了StackOverflow上的[解决方案](python-dev installation error: ImportError: No module named apt_pkg)

    我那个路径下有python3.6对应的,于是我sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

  • 我以为可以了 ,结果依旧是ModuleNotFoundError: No module named 'distutils.cmd'

  • 于是我对症下药了,我寻思已经python3默认版本改为python3.9了但是它为啥好像给python3.6安装了distutils但是没给py3.9装,于是我

    受到这个回答的启发

    Composing Programs(SICP python版) chap1 笔记_第4张图片
    sudo apt-get install --reinstall python3.9-distutils
    

    Composing Programs(SICP python版) chap1 笔记_第5张图片

  • 接下来可以了

    python3 get-pip.py

    Composing Programs(SICP python版) chap1 笔记_第6张图片

    这个问题先留个链接WARNING: The script pip3.8 is installed in ‘/usr/local/bin’ which is not on PATH,回头看看

  • 然后…

    我猜它not found的原因就是上面那个没有安装在path上?呜呜不清楚

    image-20221221200622854

  • 再接着 sudo apt install python3-pip

    可以pip3 list了,但是遇到一个warning

  • 查看一下pip和pip3

    image-20221221201532354

    Warning: pip is being invoked by an old script wrapper

    大家的做法基本是reinstall

    这个里面的最后一个解决方案好像因为他也有我上面那个遗留的问题,所以没法下一步reinstall

  • 先回头去解决上一个遗留的问题

    就像windows里面 cmd 输入path,就可以打印环境变量路径

    image-20221221202155027

    接下来按照这个教程来https://stackoverflow.com/a/70680333/18159372

    export PATH="/home/bkin/.local/bin:$PATH"
    
    source ~/.bash_profile
    
    echo $PATH
    

    看看PATH

    好像没source成功也加进去了?

    image-20221221202720838

    再pip3 list康康

    神奇,没有reinstall,这个warning就消失了

    Composing Programs(SICP python版) chap1 笔记_第7张图片

1.1.3 Interactive Sessions

  • In an interactive Python session, you type some Python code after the prompt(提示符), >>>. The Python interpreter reads and executes what you type, carrying out your various commands.

    • If you see the Python prompt, >>>, then you have successfully started an interactive session. These notes depict example interactions using the prompt, followed by some input.

      >>> 2 + 2
      4
      
  • Interactive controls.

    • Each session keeps a history of what you have typed.
    • To access that history, press -P (previous) and -N (next).
    • -D exits a session, which discards this history.
    • Up and down arrows also cycle through history on some systems.

1.1.4 First Example

soga,cs61A lec1里面用的就是这个William ShakeSpeare的例子

And, as imagination bodies forth

The forms of things to unknown, and the poet’s pen

Turns them to shapes, and gives to airy nothing

A local habitation and a name.

—William Shakespeare, A Midsummer-Night’s Dream

wow,仲夏夜之梦

  • This section:an example that uses several language features of python as a sneak preview(预览) of features to come.
  • Next section:start from scratch and build up the language piece by piece.

Python has built-in support for a wide range of common programming activities, such as manipulating text, displaying graphics, and communicating over the Internet. The line of Python code

>>> from urllib.request import urlopen

is an import statement that loads functionality for accessing data on the Internet. In particular, it makes available a function called urlopen, which can access the content at a uniform resource locator (URL), a location of something on the Internet.

Statements & Expressions.

  • Python code consists of expressions and statements(表达式和语句). Broadly, computer programs consist of instructions to either compute some value or carry out some action.

    • Statements typically describe actions. When the Python interpreter executes a statement, it carries out the corresponding action. (当 Python 解释器执行一条语句时,它会执行相应的操作)
    • On the other hand, expressions typically describe computations. When Python evaluates an expression, it computes the value of that expression.
  • The assignment statement

    >>> shakespeare = urlopen('http://composingprograms.com/shakespeare.txt')
    

    associates the name shakespeare with the value of the expression that follows =. That expression applies the urlopen function to a URL that contains the complete text of William Shakespeare’s 37 plays, all in a single text document.

    image-20221221185744707

Functions.

Functions encapsulate logic that manipulates data(函数封装了操作数据的逻辑).

  • urlopen is a function. A web address is a piece of data, and the text of Shakespeare’s plays is another. The process by which the former leads to the latter may be complex, but we can apply that process using only a simple expression because that complexity is tucked away within a function(因为这种复杂性隐藏在一个函数中).

  • Another assignment statement

    >>> words = set(shakespeare.read().decode().split())
    

    associates the name words to the set of all unique words that appear in Shakespeare’s plays, all 33,721 of them.

    The chain of commands to read, decode, and split, each operate on an intermediate computational entity(运算中间实体?): we read the data from the opened URL, then decode the data into text, and finally split the text into words(拆分为单词). All of those words are placed in a set.

    Composing Programs(SICP python版) chap1 笔记_第8张图片

问题
  • 在我的Linux虚拟机上搞这一步的时候遇到问题了

    Composing Programs(SICP python版) chap1 笔记_第9张图片

  • 尝试了这个回答里面的 https://stackoverflow.com/a/65629120/18159372

    无济于事

    哈哈要是看到旁边的votes我就不试了

    Composing Programs(SICP python版) chap1 笔记_第10张图片

  • 更奇怪的事情发生了

    我用vim写入test.py,然后再执行它,发现可以输出

    image-20221221204542516

    另外,在windows上输出words单词顺序好像不一样…? 这又是为何

    又试了一下… 我相信是网络问题了

    交互模式也可以输出,另外这次words里面的单词顺序又不一样了(

    Composing Programs(SICP python版) chap1 笔记_第11张图片

Objects.

  • A set is a type of object, one that supports set operations like computing intersections and membership.

  • An object seamlessly bundles together data and the logic that manipulates that data, in a way that manages the complexity of both.

  • Finally, the expression

    {w for w in words if len(w) == 6 and w[::-1] in words}
    {'reward', 'diaper', 'drawer', 'redder', 'repaid'}
    

    is a compound expression(复合表达式) that evaluates to the set of all Shakespearian words that are simultaneously(同时) a word spelled in reverse.
    单词和它的倒序单词同时在文本里
    The cryptic notation(神秘符号) w[::-1] enumerates(枚举) each letter in a word, but the -1 dictates to step backwards.

Interpreters.

  • Evaluating compound expressions requires a precise procedure that interprets code in a predictable way. A program that implements such a procedure, evaluating compound expressions, is called an interpreter.(解释器)

  • When compared with other computer programs, interpreters for programming languages are unique in their generality. Python was not designed with Shakespeare in mind. However, its great flexibility allowed us to process a large amount of text with only a few statements and expressions.


  • In the end, we will find that all of these core concepts are closely related: functions are objects, objects are functions, and interpreters are instances of both. However, developing a clear understanding of each of these concepts and their role in organizing code is critical to mastering the art of programming.(清楚地理解这些概念中的每一个及其在组织代码中的作用对于掌握编程艺术至关重要)

1.1.5 Errors

  • While computers are tremendously fast and flexible, they are also extremely rigid. The nature of computers is described in Stanford’s introductory course as

上面这个斯坦福cs101的链接挺有趣的

The fundamental equation of computers is:

computer = powerful + stupid

Computers are very powerful, looking at volumes of data very quickly. Computers can perform billions of operations per second, where each operation is pretty simple.

Computers are also shockingly stupid and fragile(脆弱). The operations that they can do are extremely rigid, simple, and mechanical(机械的). The computer lacks anything like real insight(真正的洞察力) … it’s nothing like the HAL 9000 from the movies. If nothing else, you should not be intimidated(恐吓) by the computer as if it’s some sort of brain. It’s very mechanical underneath it all(这一切都非常机械化).

Programming is about a person using their real insight to build something useful, constructed out of these teeny(微小), simple little operations that the computer can do.

—Francisco Cai and Nick Parlante, Stanford CS101

The rigidity of computers will immediately become apparent as you experiment with the Python interpreter: even the smallest spelling and formatting changes will cause unexpected output and errors.

Learning to interpret errors and diagnose the cause of unexpected errors is called debugging. Some guiding principles of debugging are:

  1. Test incrementally: Every well-written program is composed of small, modular components that can be tested individually. Try out everything you write as soon as possible to identify problems early and gain confidence in your components.
  2. Isolate(隔离) errors: An error in the output of a statement can typically be attributed to a particular modular component. When trying to diagnose a problem, trace the error to the smallest fragment of code you can before trying to correct it.(在尝试更正错误之前,先将错误追踪到最小的代码片段。)
  3. Check your assumptions(假设): Interpreters do carry out your instructions to the letter (一字不漏)— no more and no less. Their output is unexpected when the behavior of some code does not match what the programmer believes (or assumes) that behavior to be. Know your assumptions, then focus your debugging effort on verifying that your assumptions actually hold(验证假设是否成立).
  4. Consult others: You are not alone! If you don’t understand an error message, ask a friend, instructor, or search engine. If you have isolated an error(如果已经找出错误), but can’t figure out how to correct it, ask someone else to take a look. A lot of valuable programming knowledge is shared in the process of group problem solving.

Incremental testing, modular design, precise assumptions, and teamwork are themes that persist throughout this text. Hopefully, they will also persist throughout your computer science career.

1.2 Elements of Programming

1.3 Defining New Functions

1.4 Designing Functions

1.5 Control

1.6 Higher-Order Functions

1.7 Recursive Functions

相关资源

  • 开源书网址

你可能感兴趣的:(计算机基础,知识体系串联,python,开发语言)