From adc2e34cfcc3810dc4e8bdfbd4f6ec50f9c60a51 Mon Sep 17 00:00:00 2001 From: PARK-SEONG-HYEON <61612546+PARK-SEONG-HYEON@users.noreply.github.com> Date: Tue, 10 Mar 2020 18:00:44 +0900 Subject: [PATCH] Merge branch 'master' of https://github.com/idebtor/JoyAI --- GitHubWikis.md | 6 +- ipynb/01Overview.ipynb | 1354 ---------------------------- ipynb/02DataTypes.ipynb | 1757 ------------------------------------- ipynb/Lec00Overview.ipynb | 609 ++++++------- 4 files changed, 275 insertions(+), 3451 deletions(-) delete mode 100644 ipynb/01Overview.ipynb delete mode 100644 ipynb/02DataTypes.ipynb diff --git a/GitHubWikis.md b/GitHubWikis.md index eb0d3ce..c8bbbb4 100644 --- a/GitHubWikis.md +++ b/GitHubWikis.md @@ -1,9 +1,5 @@ # Welcome to GitWikis ------------------------- -Good FAQ Web Site: [here](https://www.git-tower.com/learn/git/faq/) - - [Merge conflict](https://www.git-tower.com/learn/git/ebook/en/command-line/advanced-topics/merge-conflicts) - - [Difference between fetch & pull](https://www.git-tower.com/learn/git/faq/difference-between-git-fetch-git-pull) ------------------------ +--------------------------------------------- ### 1. local repository files을 모두 origin/master와 강제로 동기화(Overwrite)하기 GitHub Desktop은 Git의 일부 중요한 기능(명령)만을 발췌하여 쉽게 사용하도록 만든 윈도우 인터페이스 적용한 프로그램입니다. 그러므로, 좀 자세하고, 다양한 Git의 기능을 사용하려면, Console에서 Git 명령어를 사용하여 우리가 필요한 작업을 해야합니다. Git을 사용하려면, git도 설치해야 합니다. diff --git a/ipynb/01Overview.ipynb b/ipynb/01Overview.ipynb deleted file mode 100644 index 1b329eb..0000000 --- a/ipynb/01Overview.ipynb +++ /dev/null @@ -1,1354 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Welcome to \"CrushPython\"\n", - "\n", - "The fear of the LORD is the beginning of knowledge, but fools despise wisdom and discipline. Proverbs 1:7\n", - "\n", - "-------" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Greetings!\n", - "May I personally extend a warm welcome to you who are willing to come to this class. I hope that we can make this course of time will be memorable and enjoyable with a new spirit of learning together. \n", - "\n", - "This is a short course on Python for students who have some experience of programming in a programming language other than Python. The course assumes that you know no Python whatsoever. Also, those people who already have considerable programming experience in several different programming languages are likely to be bored, and would be better off just working through the notes in their own time, or looking at one of the many on-line Python tutorials. \n", - "\n", - "__Python is named after Monty Python’s Flying Circus, not the constricting snake.__\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## \"Happy Coding!\" " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Piazza\n", - "\n", - "You will use Piazza as a forum for discussion, to find team members, to arrange appointments, and to ask questions. Piazza should be your primary form of communication with the staff and me. All readings, homeworks, and project descriptions will be announced on Piazza as well. \n", - "Go to [Piazza](https://piazza.com/) and login for the class. Let us know if you have not been invited yet to join in piazza yet. \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Programming expectations\n", - "\n", - "All the assignments and labs for this class will use Python and, for the most part, the browser-based IPython notebook format you are currently viewing as well as a command-line mode and Python Tools for Visual Studio when needed. Knowledge of Python is not a prerequisite for this course, **provided you are comfortable learning on your own as needed**. While we have strived to make the programming component of this course straightforward, we will not devote much time to teaching Python syntax itself. Basically, you should feel comfortable with:\n", - "\n", - "* How to look up Python syntax on Google and StackOverflow.\n", - "* Basic programming concepts like functions, loops, arrays, dictionaries, strings, and if statements.\n", - "* How to learn new libraries by reading documentation.\n", - "* Asking questions on StackOverflow or Piazza.\n", - "\n", - "There are many online tutorials to introduce you to [Python training courses](https://www.enthought.com/services/training/) and [scientific Python programming](https://github.com/jrjohansson/scientific-python-lectures).\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Introduction\n", - "\n", - "---------\n", - "\n", - "# Python - Easy to learn, but powerful\n", - "\n", - " - Readability\n", - " - Simplicity\n", - " - Extensibility" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Getting Python\n", - "\n", - "You will be using Python 3.x or latest (not 2.x) throughout the course, including many popular 3rd party Python libraries or modules. There are many ways of installing Python. \n", - "\n", - "For the program development environment, you may use any kind of IDE. Personally, I have reviewed or used a few IDE’s such as Anaconda, Canopy, Eclipse, and PyCharm. At this point I ended up using [Anaconda](http://continuum.io/downloads) and 64 bit Python executable. It comes with an easy-to-install bundle of Python and 3rd party libraries. \n", - "\n", - "In this first class, we will be using a variety of data types of Python and understand the basic concepts of the language to ensure everything goes smoothly moving forward, While some of this will likely be dull, doing it now will enable us to do more exciting work in the days that follow without getting bogged down in further software development. It is essential that you complete it timely. \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## MOOC & Textbook Available\n", - "\n", - "We are going to use the one of the best Python course available through www.coursera.org or available for free at www.py4e.com.\n", - "\n", - "The book \"Python for Everybody\" by Charles R. Severance available for free in many different forms including html and pdf. \n", - "- https://www.py4e.com/book\n", - "- over 200 pages long.\n", - "\n", - "Coursera offers a week for free, and $49 per month when you subscribe it.\n", - "- You may earn a Coursera Certificate for this course\n", - "\n", - "\"Python for Everybody\" is designed to introduce students to programming and software development through the lens of exploring data.\n", - "This course consists of five parts as shown below:\n", - "\n", - "1. Programming for Everybody (Getting Started with Python)\n", - "2. Python Data Structures\n", - "3. Using Python to Access Web Data\n", - "4. Using Databases with Python\n", - "5. Capstone: Retrieving, Processing, and Visualizing Data with Python\n", - "\n", - "In this specialization, I expect you are to finish 4 out of 5 parts.\n", - "I hope that you take this course along with a Certification specialized in Python.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## MOOC Pye4 Lessons for 모인활(AI Applications for All) Class\n", - "Every student is expected to go through the the following topics on [PY4E online lessons](https://www.py4e.com/lessons). Submit the screen capture of the final grade on Piazza by the end of 7th week of this semeter. You may check [the due date](https://piazza.com/class/k7222vwq8y61ni) for each lesson in Piazza.\n", - "\n", - " 2. Why Program?\n", - " 3. Variables, expression and statement\n", - " 4. Conditional Execution\n", - " 5. Function\n", - " 6. Loops and Iterations\n", - " 7. Strings\n", - " 9. Lists" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Python Installation Guide\n", - "\n", - "Refer to Course Web Site: www.py4e.com\n", - "\n", - "https://www.py4e.com/lessons/install" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Python or IPython?\n", - "IPython is short for __I__nteractive __Python__. It does all things Python does and more. It provides a rich architecture for interactive computing with:\n", - "- A browser-based notebook with support for code, text, mathematical expressions, inline plots and other rich media.\n", - "- Support for interactive data visualization and use of GUI toolkits.\n", - "- Flexible, embeddable interpreters to load into your own projects.\n", - "- Easy to use, high performance tools for parallel computing.\n", - "Once again all Python scripts presented here should work in IPython seamlessly, but also provides you with more functionalities and rich set of tools. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## IPython or Jupyter Notebook?\n", - "The Jupyter Notebook is a web-based interactive computational environment where you can combine code execution, text, mathematics, plots and rich media into a single document. These files have **ipynb** extensions. A notebook consists of a series of cells which contains either code or document. \n", - "\n", - "- If you are new to Python see http://python.org - it will be best to spend some time learning basic Python syntax before attempting the interactive parts of these lessons.\n", - "\n", - "- If you are new to Jupyter Notebook see http://ipython.org/notebook - prepare to be impressed.\n", - "\n", - "- If you are new to numpy/scipy/matplotlib/pandas see http://www.scipy.org/ - it is not necessary to have a mastery of all these to get value out of these lessons. However the more you know these technologies the faster you will be able to apply these techniques immediately.\n", - "\n", - "We'll be using them to complete labs and homework. Once you've set up Python, please get this file from Piazza or Dropbox folder as informed.\n", - "Then, open it with IPython by typing\n", - "\n", - "```\n", - "jupyter notebook \n", - "```\n", - "\n", - "For the rest of the assignment, use your local copy of this page, running on IPython.\n", - "\n", - "Notebooks are composed of many \"cells\", which can contain text (like this one), or code (like the one below). Double click on the cell below, and evaluate it by clicking the \"play\" button above, for by hitting `` or ``." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Tutorial for Jupyter Notebook\n", - "- In-depth [video by developer](https://www.youtube.com/watch?v=XFw1JVXKJss) by its creator, Fernando Perez, in PyCon 2014 \n", - "- [Introductory Video by SimpiLearn](https://www.youtube.com/watch?v=3C9E2yPBw7s)\n", - "- It is a must to watch!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---------\n", - "\n", - "# 1. Overview\n", - "\n", - "In this Jupyter Notebook, we will cover a wide variety of topics about the Python language to give you a broad overview of the data structures it offers, some use cases for them and the kinds of tasks they can be used for. \n", - "\n", - "__NOTE__: It isn't expected for new comers to be able to follow all the details presented here. This fast-paced overview will be followed with a slower in-depth coverage of all these topics.\n", - "\n", - "__NOTE__: The following materials have been collected from the numerous sources including my own and my students over the years of teaching and experiences of programming. Please help me to keep this tutorial up-to-date by reporting any issues or questions. Send any comments or criticisms to `idebtor@gmail.com`. Your assistances and comments will be appreciated." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Code cell or Markdown cell\n", - "Jupyter Notebook consists of a series of so-called cells. There are two types of cells that contains either code or document. Cells that contains code is called __code cell__, whereas cell that contains document is called __markdown cell__. \n", - "\n", - "By default, the notebook creates a code cell. Let's explore working with code cells. You may convert a code cell into a markdown cell by typing a short-cut ``, `` vice versa. \n", - "\n", - "#### Code cells\n", - "May contain python code and ipython magic.\n", - "\n", - "#### Markdown cells\n", - "Contains documents written in Markdown which is a lightweight markup language with plain-text-formatting syntax. It is a kind of simple form of HTML. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Cell menu\n", - "The \"Cell\" menu has a number of menu items for running code in different ways. These includes:\n", - "\n", - "- Run and Select Below\n", - "- Run and Insert Below\n", - "- Run All\n", - "- Run All Above\n", - "- Run All Below\n", - "\n", - "----------" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Running Cells\n", - "Jupyter notebook cell is capable of running code in a wide range of languages. However, the default kernel in Jupyter notebook runs Python code. If the cell is a markdown cell, it just randers into webpage. \n", - "\n", - "Run a cell using `````` or \"Run Cell\" button in the toolbar above:\n", - "\n", - "There are two other keyboard shortcuts for running code:\n", - "\n", - "- `Alt+Enter` runs the current cell and inserts a new one below.\n", - "- `Ctrl+Enter` run the current cell and enters command mode." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 2. Run OS or cell magic commands in code cell\n", - "\n", - "IPython uses ! to run shell commands. Jupyter notebook provides shell-like magic functions as well. The followind commands available are shown below: \n", - "\n", - "```\n", - "%cd, %cat, %cp, %env, %ls, %man, %mkdir, %more, %mv, %pwd, %rm, %rmdir\n", - "```\n", - "\n", - "These commands can be used without the `%` sign if automagic is on. This makes it so that you can almost treat the IPython prompt as if it's a normal shell:\n", - "\n", - "- Use `%` to run the OS command in code cell. \n", - "- You even omit `%`since, automagic option is on by default. \n", - "- Some developers prefer to using `!` instead of `%` since IPython uses `!` for a long time." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 1. Print the current folder name (present working directory).\n", - "- Try `%pwd` with % and without %, or with !.\n", - "- `pwd` means `present working directory` or `print working directory`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 2. Print the list of files in the current folder.\n", - "- Try it with `%ls` and `%dir`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 3. Print the contents of a file. \n", - "- Try it with `%cat ` and `%type `" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "------------\n", - "\n", - "\n", - "# 3. Run Python code in code cell\n", - "\n", - "## Arithmetic\n", - "Let's start simple with some arithmetic..." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Add two integer numbers. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Add two floating pointer numbers." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If you add an integer to a decimal, you will get a floating point number." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "How about computing `2**8, 2**16, 2**32`?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Variables (or names)\n", - "You can save your value into a name called 'variable'." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Save the values 10 and 5 in the variables 'a' and 'b', respectively. \n", - "# print a, b\n", - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Now you can do some math with two variables. \n", - "# Add two numbers and save the result to another variable 'c'.\n", - "# Subtract two numbers (a - b) and save the result to another variable 'd'.\n", - "# print the results c and d\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Getting an input from the user and save it \n", - "\n", - "The varable 'name' stores a string value, not numeric value.\n", - "- use `input()` function to get an user's input." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ask a name (`What is your name? `) and save it in a variable called `name`. Then, you print `Hello ` and the name entered as shown below:\n", - "\n", - "For example, \n", - "```\n", - "What is your name?\n", - "John\n", - "Hello John!\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Ask an age (`What is your age? `)and save it in a variable called `age`. Print his or her age but one year older that user's input at the end of this prompt: `In a few days, you becomes`. Note: `age` is a string type. Use `int()` to change a string to int. \n", - "\n", - "Sample Run:\n", - "```\n", - "What is your age?\n", - "33\n", - "In a few days, your age becomes 34\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## List\n", - "Python makes it easy to create lists, which can contain any kind of object. We can index these, concatenate them, and find the length, just as we can with strings. For more examples, refter to [Python Tutorials](https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehension#more-on-lists)\n", - "\n", - "#### 1. Create two lists, one with raibow colors and the other with a few prime numbers:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']\n", - "primes = [2, 3, 5, 7, 11, 13]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 2. Make a new list called `mixed` by adding two lists ." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 3. How many elements are in the `mixed`?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 4. What are the first and last elements in the `mixed`?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 5. Append the next prime number (17) at the end of the `mixed`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Reading a web page\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import requests \n", - "response = requests.get('http://www.handong.edu') \n", - "response.ok" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Display the first 1000 characters from the response. Use `response.text[1000]`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "response.text[:500]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Read a remote file and process the text" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from urllib.request import urlopen \n", - "book = urlopen('http://www.gutenberg.org/cache/epub/10/pg10.txt')\n", - "#book = urlopen('http://composingprograms.com/shakespeare.txt')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 1. Make a list words out of the book read from url." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "wlist = book.read().decode().split()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 2. Get the number of words in `wlist`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 3. Check the first 10 words in `wlist`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 4. Sort words in `wlist`. \n", - "\n", - "- Use the list's method called `sort()`\n", - "- To find methods available, Use after the class/variable name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 5. Check the first 10 words in `wlist` after `sort()`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 6. Count a specific word `truth` in `wlist` or the Bible." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 7. Remove duplicated words and check its length(or number of words). \n", - "- Use `set()` function returns unique elements in a set type which is unordered or a kind of bag.\n", - "- Therefore, the set data type does not support indexing." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - " ulist[:10] # set is not subscriptable; read the error message" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 8. Convert a set data type object into a list type and sort elements in it.\n", - "- Use list() function to convert a set object to a list object." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 9. Find the last word in alphabetical order in the word list.\n", - "- sort the list first. \n", - "- print last 10 words in the list." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 10. Find the longest word in the book.\n", - "- Use `max()` function with `key=len` argument." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 11. Find emornilap in the book.\n", - "\n", - "#### What's an Emordnilap?\n", - "\n", - "Emordnilaps are like palindromes' evil twins. Instead of being the same word, these rare words make a different real word when spelled backward! Reverse the word \"stop\" and it becomes \"pots.\" Flip \"drawer\" and you get \"reward.\" English contains a surprising variety of words that change meanings as soon as you read them right to left.\n", - "\n", - "Emordnilap Examples: \n", - " - desserts and stressed, \n", - " - decaf and faced\n", - " - edit and tide\n", - " - deeps and speed" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### a pythonic way - using list comprehension" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Functions\n", - "\n", - "Now let's take a look at defining and using functions in Python. We will start by defining a function to evaluate a polynomial." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Defining your own function\n", - "\n", - "- Define a function if you are using the same set of code more than once. \n", - "- Be careful when using `:` and `` characters.\n", - "\n", - "\n", - "#### 1. Do the following task three times: \n", - "`\n", - "Ask a name to a person and say 'Hello` to him/her. . \n", - "`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 2. Draw a linear graph ` y = x ` or `x = 1, 2, 3, 4 and y = 1, 2, 3, 4`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "%matplotlib inline\n", - "\n", - "plt.plot(None, None)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 3. Plot a polynomial from `x = -10` and `x = 10 `.\n", - "- Its coefficients are `a = 1, b = 2, c = 3`\n", - "- Define a polynomial, ` y = a * x^^2 + b * x + c ` that returns` y`. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def poly(x, a, b, c):\n", - " None\n", - " return None" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "%matplotlib inline\n", - "\n", - "x = None\n", - "y = None\n", - "plt.plot(None, None)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 4. Draw `cos(x)` function from `x = 0` and `x = 2 * pi`.\n", - "\n", - "- To check x values, evaluate x after generating numbers using np.arange()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "x = np.arange(0, 2 * np.pi, 0.1)\n", - "plt.plot(x, np.cos(x))\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Image Display\n", - "\n", - "The pictures and more exotic objects can also be displayed, as long as their representation supports the IPython display protocol." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "from matplotlib.image import imread\n", - "#%matplotlib notebook \n", - "\n", - "img = imread('https://github.com/idebtor/KMOOC-ML/blob/master/ipynb/images/lenna.png?raw=true')\n", - "plt.imshow(img)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Class and Object" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now lets create a class. In Python, every class should derive from object. Our class will describe a person, with a name and an age. We will supply a constructor, and a method to get the full name.\n", - "- How to create a class: Refer to [Wikibook](http://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "class Person(object):\n", - " def __init__(self, first, last, age):\n", - " self.first = first\n", - " self.last = last\n", - " self.age = age\n", - " \n", - " def full_name(self):\n", - " return self.first + ' ' + self.last" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now we can create an instance of a Person, and work with the attributes of the class." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "person = Person('Lee', 'Handong', 21)\n", - "person.first" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "person.last" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "person.full_name()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "person.last = 'Kim'" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In Python, we can add new class attributes on the fly, even if they have not been defined yet." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "person.smoke = False\n", - "person.smoke" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Writing a code cell into a file \n", - "\n", - "You may use __%%writefile__ cell magic command. You have to place the command at the very first line of the code cell.\n", - "```\n", - "%%writefile mycode.py\n", - "```\n", - "\n", - "\n", - "## Loading external codes\n", - "\n", - "- Drag and drop a .py in the dashboard\n", - "- Use __%load__ with any local or remote url: the Matplotlib Gallery http://matplotlib.org/gallery.html\n", - "\n", - "```\n", - "%load mycode.py\n", - "```\n", - "\n", - "In this notebook we've kept the output saved so you can see the result, but you should run the next cell yourself (with an active internet connection).\n", - "\n", - "----------" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 4. Run Markdown cell \n", - "\n", - "Markdown is a lightweight markup language with plain-text-formatting syntax. Its design allows it to be converted to many output formats, but the original tool by the same name only supports HTML." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Markdown Summary \n", - "Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown. Mostly, Markdown is just regular text with a few non-alphabetic characters thrown in, like # or *.\n", - "\n", - "      __Desired style__      __in Markdown syntax__      __in HTML syntax__\n", - "```\n", - "Heading 1\t # Title

Title

\n", - "Heading 2\t ## Title

Title

\n", - "Heading 3\t ### Title

Title

\n", - "Heading 4\t #### Title

Title

\n", - "\n", - "Paragraph Just start typing

Just start typing

\n", - " \n", - "Bold **Text** Text\n", - "Italic *Text* Text\n", - "Strike ~~Text~~ Text\n", - " \n", - "List (unordered) * List item 1

  • List item 1
  • \n", - " * List item 2
  • List item 2
  • \n", - " * List item 3
  • List item 3
\n", - "\n", - "List (ordered) 1. List item 1
  • List item 1
  • \n", - " 1. List item 2
  • List item 2
  • \n", - " 1. List item 3
  • List item 3
\n", - "\n", - "Images\t ![Alt text](path/image.jpg)\t \"Alt\n", - "Hyperlinks\t[Link text](https://kmooc.kr/)\tLink text\n", - "\n", - "Quoted (indent) > Text

Text

\n", - "Code (inline) ``Statement`` Statement\n", - "Code (fenced)\t ```
Statement   \n",
-    "                  Statement 1               1Statement\n",
-    "                  Statement 2               2Statement\n",
-    "                  Statement 3               3
\n", - " ``` \\\n", - "``` " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Examples: Markdown in action\n", - "\n", - "Some examples of Markdown: " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Title\t- Heading 1\t\n", - "## Title - Heading 2\n", - "### Title - Heading 3\n", - "#### Title - Heading 4\t" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Bold Text**   __another bold text__ \n", - "*Italic Text*   _another italic text__ \n", - "~~Text~~ " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* unordered list\n", - "* apple\n", - "* orange\n", - "- ANOTHER unordered list\n", - "- apple\n", - "- orange\n", - "\n", - "\n", - "1. ordered list\n", - "2. second\n", - "3. third" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "[Welcome to Handong Global University](https://www.handong.edu)\n", - "\n", - "\n", - "
그림 3: 숫자 인식 인공 신경망
" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "``` \n", - "This is a quote.\n", - "\n", - "# Title\t- Heading 1\t\n", - "## Title - Heading 2\n", - "### Title - Heading 3\n", - "#### Title - Heading 4\t\n", - "```\n", - "\n", - "> This is block quote \n", - ">\n", - "> God is good all the time. \n", - "> All the time God is good. \n", - "> (There are two hidden spaces after \"all the time.\" and \"God is good.\" that makes a new line.\n", - "> Otherwise, it will display two line into one like these two sentences.)\n", - "\n", - "\n", - "`-----------` This draws a following line. \n", - "\n", - "-------\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LaTex \n", - "\n", - "LaTeX is a high-quality typesetting system; it includes features designed for the production of technical and scientific documentation. LaTeX is the de facto standard for the communication and publication of scientific documents. LaTeX is available as free software.\n", - "\n", - "For example:\n", - "\n", - "$$ D = \\sqrt{b^2 + 4ac} $$\n", - "\n", - "\\begin{align}\n", - "z = w_0x_0 + w_1x_1 + ... + w_m x_m = \\sum_{j=0}^{m} x_j w_j = \\mathbf{w^Tx}\n", - "\\end{align}\n", - "\n", - "$ D = \\sqrt{b^2 + 4ac}$ \\\n", - "$ z = w_0x_0 + w_1x_1 + ... + w_m x_m = \\sum_{j=0}^{m} x_j w_j = \\mathbf{w^Tx} $\n", - "\n", - "---------" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 5. A simple way to start Jupyter notebook in Windows\n", - "To start an Jupyter Notebook, you create a console window first, then you type \"jupyter notebook\" and options in the command-line prompt. Then you still need to navigate to file folders where your Jupyter Notebook files(~.ipynb) are. It is cumbersome. \n", - "\n", - "I created a batch file (`_start_ipynb.bat`) as shown below and place it in the folder where I want to start Jupyter Notebook from. In my case, I placed it in folders where my notebooks exist such as `~/Dropbox` and `~/Dropbox/CrushPython`. Then starting jupyter notebook is __a double clicks away__. Enjoy it. \n", - "\n", - "The batch filename I use is `_start_ipynb.bat` since the file is usually displayed at the top in the folder view because of the prefix `_`,\n", - "```\n", - "rem start jupyter notebook here .bat file \n", - "rem If ~.py file to be written as well, then use jupyter notebook --script \n", - "dir \n", - "jupyter notebook \n", - "pause \n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 6. Shell\n", - "\n", - "In computing, a shell is a user interface for access to an __operating system's services__. In general, operating system shells use either a command-line interface (CLI) or a graphical user interface (GUI), depending on a computer's role and particular operation. It is named a __shell__ because it is the outermost layer around the operating system.\n", - "\n", - "One problem we are facing when using Shell is that every OS has its own shell. They are all different, but there are aliases available we can use the same shell command-like across the OS's at convenience." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Some shell commands are often used.\n", - "- `cd mydir` changes directory to `mydir`. \n", - "- `cd ..` moves to the parent directory of current directory, or the directory one level up from the current directory. “..” represents parent directory.\n", - "- `cd ~` moves to directory to the home directory. \n", - "- `/` on its own is the root directory of the whole file system.\n", - "- `..` means ‘the directory above the current one’; . on its own means ‘the current directory’.\n", - "- A relative path specifies a location starting from the current location.\n", - "- An absolute path specifies a location from the root of the file system.\n", - "- Directory names in a path are separated with `/` on Unix/Linux/macOS, but `\\` on Windows.\n", - "\n", - "- `cp old new` copies a file.\n", - "- `mkdir path` creates a new directory.\n", - "- `mv old new` moves (renames) a file or directory.\n", - "- `rm path` removes (deletes) a file.\n", - "- `*` matches zero or more characters in a filename, so `*.txt` matches all files ending in `.txt`.\n", - "- `?` matches any single character in a filename, so `?.txt` matches `a.txt` but not `any.txt`.\n", - "- The shell does not have a trash bin: once something is deleted, it’s really gone." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Exercise: Creating and deleting a folder and file.\n", - "1. Check the current directory and know where you are now.\n", - "1. Create a `myfolder` directory. \n", - "1. Change directory to `myfolder`.\n", - "1. Check the current working directory\n", - "1. Create a file called `hello.txt` which contains \"Hello World\".\n", - "1. Check that you have the file just created.\n", - "1. Check the file contents just created.\n", - "1. Delete the file and directory you just created.\n", - "1. Remove the directory `myfolder`. \n", - " - `cd ..` first since you cannot remove the folder, then remove the folder." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### a solution:\n", - "1. pwd\n", - "1. \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Closing and Tips on Jupyter Notebook\n", - "\n", - "That gives you a quick tour of the capabilities of Jupyter notebook or IPython. \n", - "\n", - "We covered a lot of ground here, but this should give you an idea of the power that Python puts at your fingertips. In the later lectures, we will give you a more in-depth tour of most of these features.\n", - "\n", - "When you execute code somewhere in the middle of a notebook, the code fragment may be dependent on imports, intermediate results in local variables and other such initializations in preceding cells. So it is better to execute code cells sequentially, starting at the top, when new to IPython Notebook, to avoid being confused by such extraneous errors.__ \n", - "\n", - "Even so if you want to dive in and not have to execute each preceding code cell then you'll need to execute the menu item 'Cell->Run All'. This executes each code cell for you sequentially once, so from that point on all dependencies on prior code cells are satisfied." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "-------\n", - "__Be joyful always!__ 1 Thes.5:16" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.3" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/ipynb/02DataTypes.ipynb b/ipynb/02DataTypes.ipynb deleted file mode 100644 index da41b4e..0000000 --- a/ipynb/02DataTypes.ipynb +++ /dev/null @@ -1,1757 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Welcome to CrushPython\n", - "\n", - "-------\n", - "So tell them, 'As surely as I live, declares the LORD, I will do to you the very things I heard you say.' Numbers 14:28 \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__NOTE:__ The following materials have been adpated from the numerous sources including Python and Canopy web sites including my own. Please help me to keep this tutorial up-to-date by reporting any issues or questions. Send any comments or criticisms to `idebtor@gmail.com` Your assistances and comments will be appreciated. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "------\n", - "\n", - "## Revisit: Tips on IPython magics\n", - "Magics is a user-definable mini command language in IPython. Magics come in two kinds:\n", - "- __Line magics:__ prepended by one `%` character and whose arguments only extend to the end of the current line.\n", - " ```\n", - " %pwd : print curren working directory\n", - " %ls : list the file names in the current working directory\n", - " %cd 'dir': changes to directory 'dir'.\n", - " %cd -: changes to the last visited directory.\n", - " %load 'source': load 'source' file into the current cell.\n", - " %run 'source': run 'source' file\n", - " %timeit : time execution of a statement or expression in line\n", - " ```\n", - "- __Cell magics:__ These use two percent characters as a marker (`%%`), and they receive as argument both the current line where they are declared and the whole body of the cell.\n", - " ```\n", - " %%writefile 'source': write/overwrite the cell to 'source' file.\n", - " %%timeit : time execution of code in cell \n", - " ```\n", - " \n", - " \n", - "__Note__: Automagic is ON, % prefix IS NOT needed for line magics. \n", - "\n", - "__Recall__: `` executes the command in the current cell and stays there.\n", - "\n", - "\n", - "- A text file can be loaded in a notebook cell with the magic command %load.\n", - "```\n", - " %load filename.py\n", - "``` \n", - "- To save the cell content back into a file add the cell-magic `%%writefile filename.py` at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be __silently overwritten__. For example:\n", - "```\n", - " %%writefile foo.py\n", - " print('Hello World')\n", - "```\n", - "- To run the foo.py script file saved above:\n", - "```\n", - " %run foo\n", - "```\n", - "- To list all available magics available: \n", - "```\n", - " %lsmagic\n", - "```\n", - "- To see the help any the magic command add a `?`: like `%load?` or `%%writefile?`.\n", - "- For general help on magic functions type `%magic` For a list of the available magic functions, use `%lsmagic`. For a description of any of them, type `%magic_name?`, e.g. `%cd?`.\n", - "\n", - "See also: [Magic functions](http://ipython.org/ipython-doc/dev/interactive/tutorial.html#magic-functions) from the official IPython docs.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Exercise\n", - "\n", - "1. Save the following cell in `lenna.py`.\n", - "1. Read `lenna.py` file into a cell.\n", - "1. Run the code and measure the execution time.\n", - "\n", - "__hint:__ writefile, load, timeit" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "from matplotlib.image import imread\n", - "%matplotlib inline\n", - "\n", - "img = imread('https://github.com/idebtor/KMOOC-ML/blob/master/ipynb/images/lenna.png?raw=true')\n", - "None" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__a solution__:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "----------\n", - "\n", - "# Lesson - Data Types and Operations\n", - "\n", - "Let's take a look at the common numerical data types, string, bool and some other data types.\n", - "\n", - "- __int__ - integers: ..., -3, -2, -1, 0, 1, 2, 3, ...\n", - "- __float__ - floating point numbers, decimal point fractions: -3.1, 1.5, 1e-8, 3.141592e5\n", - "- __str__ - character strings, text: \"WhynotPython\", 'python', '3.16'\n", - "- __bool__ - boolean values: `True` and `False`\n", - "- __complex__ - A complex number is defined using a real component + an imaginary component j\n", - "\n", - "\n", - "- __list__ - An ordered list of items : `[ 1, 5.3, 'Hello']`\n", - "- __tuple__ - Tuples are immutable lists, while the list data can be modified, : `(1, 3, 5)`\n", - "- __dict__ - Dictionaries are made up of key: value pairs: `{\"Lee\": 8 , \"Kay\": 5}`\n", - "- __set__ - An unordered collection of data type without duplicate elements: `{1, 2, 'hello`}`" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## int - Integer data type\n", - "\n", - "The first of these is the integer type. We can add integers, getting another integer as the result:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1 + 2" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also assign an integer to a variable:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 3 + 4" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can ask the variable for its type, and see that it is `int`:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "256*256 # 2**8 * 2**8 = 2**16" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "65536 * 65536 # 2**32" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "4294967296 * 4294967296 # 2**64" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 18446744073709551616 * 18446744073709551616 # 2*132" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "type(a)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a ** 1000" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__NOTE__: There is no longer a limit to the value of integers. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## float - Floating Point Numbers\n", - "\n", - "You can represent real numbers in Python as easily as integers. You may use `float()` to convert `int` to `float` data type. For example,\n", - "#### Convert `int` to `float` using `float()`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 5\n", - "a = 1.2345\n", - "type(a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Notice that the type of `a` is now `float`.\n", - "\n", - "This can be generalized for other numeric types: `int()`, `complex()`. It is called __type conversion__.\n", - "\n", - "#### convert `float` to `int` using `int()`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# float to int \n", - "int(1.12345)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# float a = -1.98765 to int \n", - "a = -1.98765\n", - "a = int(a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Notice__ that int() type conversion always __rounds towards 0__.\n", - "\n", - "You may apply it for complex number as well." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# floating point number in string \n", - "complex('123.4')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Even you can convert a number in string as well." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "int('123')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "float('123.4')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Str - string data type\n", - "\n", - "Another built-in Python data type is strings. Strings are sequences of letters, numbers, symbols, and spaces. In Python, strings can be almost any length and can contain spaces. Strings are assigned in Python using single quotation marks ' ' or double quotation marks \" \".\n", - "\n", - "- To represent a string, you may use a pair of single, double, or triple of double quations. Use a triple quote to have a multiple lines of comments. \n", - "\n", - "- For example\n", - "```\n", - " 'Hello World' \n", - " \"Hello World\"\n", - " \"\"\"Hello World\"\"\"\n", - " 'Hello \"Mr. Kim\"'\n", - "```\n", - "- `print()` function - prints a textual representation to the console" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 'Hello World'\n", - "type(a)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "b = \"Hello World\"\n", - "type(b)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(\"Hello World\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(\"Hello\", 'World')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(\"Hello\" + 'World')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 1: \n", - "How do you print the follwoing sentence as shown exactly?\n", - "```\n", - "Hello \"Mr. Kim\"\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(None)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 2:\n", - "\n", - "How do you print the follwoing sentence as shown exactly?\n", - "```\n", - "-----------------------------------\n", - "| Hello World, God loves you all. |\n", - "-----------------------------------\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "-----------------------------------\n", - "| Hello World, God loves you all. |\n", - "-----------------------------------\n", - "\n" - ] - } - ], - "source": [ - "print(None)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Dynamically typed vs Strongly typed \n", - "\n", - "Let's assign a value of float type to complex type `a`. Then see what will happen. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 1 + 2j\n", - "a = 1.4\n", - "type(a)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Wow! The assignment works (different from C/C++, java) and the type of the variable `a` is _dynamically_ changed from complex to the new type - string. So, Python is called __a dynamically typed language__. \n", - "\n", - "Then will the following code work? " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = \"Believe\"\n", - "b = 2\n", - "c = \"See\"\n", - "print(a + b + c)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It did not work. \n", - "Many operations in Python depend on their types. So, Python is called __a strongly typed language__\n", - "\n", - "To fix the problem, we need to convert the type of the variable `b` to string. A built-in function `str()` converts the `int` type into a `str` type. Also compare the output of two print statements.\n", - "\n", - "#### Example 1. Fix the following code such that it prints `Believe2See`. \n", - "- Pay attention to the difference between two `print()` functions below:" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "ename": "NameError", - "evalue": "name 'a' is not defined", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# fix this line\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mc\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# it produeces 'Believe 2 See'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;31mNameError\u001b[0m: name 'a' is not defined" - ] - } - ], - "source": [ - "print(a + None + c) # fix this line\n", - "print(a, b, c) # it produeces 'Believe 2 See' " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "------------\n", - "## Arithmetic Operations\n", - "\n", - "Let's use an example of a more involved numerical expression to get some familiarity with Python's operation syntax and order of operations." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Evaluate `1 - 4 * 2**3 - 60 // 7 + 89 % 98`" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Looking at this, most of the operations should be straightforward, but `**` in Python indicates exponentiation, and `%` is the modulo (or remainder) operation.\n", - "\n", - "Python's precedence order for operations is fairly standard (from highest to lowest):\n", - "\n", - "* `( )` (parenthesis grouping)\n", - "* `**` (exponentiation)\n", - "* `*` (multiplication), \n", - "* `/`(true division), \n", - "* `//`(integer division) - also called __floor division__ since applying the floor function after division.\n", - "* `%`(modulus) - remainder of the division of the two operands, rather than the quotient\n", - "* `+`, `-` (addition, subtraction)\n", - "\n", - "Example 1: `6%2` evaluates to `0` because there's no remainder if 6 is divided by 2 ( 3 times ).\n", - "\n", - "Example 2: `7%2` evaluates to `1` because there's a remainder of 1 when 7 is divided by 2 ( 3 times ).\n", - "\n", - "Example 3: `4*2**3` evaluates the exponentiation part first and multiplication. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "4 * 2**3" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "So we now have `1 - 32 - 60 // 7 + 89 % 98`.\n", - "\n", - "The next operations are multiplication, integer division // and modulo. Be caucious when there is a negative number in modulo operation. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "60 // 7, 89 % 98" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the expression simplifies to `1 - 32 + 8 + 89`." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "print(1 - 4*2**3 - 60 // 7 + 89 % 98) \n", - "print(1 - 32 - 8 + 89)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluate the following expressions: \n", - "\n", - "#### Example 1: Print each digit in a three-digit number." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "digits = 248\n", - "digit1 = None\n", - "digit2 = None\n", - "digit3 = None\n", - "print(digit1)\n", - "print(digit2)\n", - "print(digit3)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 2: Evaluate the expression." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "((2 * 3 + 4) / 5) ** 2 % 3" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 3: Limitations of floating point representation\n", - "\n", - "- Beware that due to the limitations of [floating point arithmetic](https://en.wikipedia.org/wiki/Floating-point_arithmetic), rounding errors can cause unexpected results. \n", - "\n", - "- [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/2/tutorial/floatingpoint.html)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 0.6/0.2\n", - "a" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 0.6//0.2\n", - "a" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 4:\n", - "\n", - "Let's do the same thing as done above but with `a = 1.4 - 1.0` and see what happens." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 1.4 - 1.0\n", - "if (a == 0.4):\n", - " print('yes, it is 0.4')\n", - "else:\n", - " print('no, it is not 0.4')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1.4 - 1.0" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1.6 - 1.0" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 5:\n", - "\n", - "Write a code that accepts an age from user and display the result as shown below. You may need to use `int()` and `input()`. \n", - "\n", - "```\n", - "What is your age?\n", - "7\n", - "Your age becomes 8 tomorrow. \n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "age = None\n", - "print('your age becomes ', None, 'tomorrow.')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Simple Math Functions\n", - "\n", - "There are a number of simple math functions that are available in Python, and we'll show a few here to give you an idea.\n", - "\n", - "```\n", - " abs()\n", - " round()\n", - " max()\n", - " min()\n", - "```\n", - "\n", - "You can get the absolute value with `abs()`:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "abs(-3)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "You can round a floating point number to the nearest whole number using `round()`:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "round(2.718281828)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And you can use `max()` and `min()` functions to compute minimum and maximum values from a collection of values:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "max(0, min(10, -1, 4, 3))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This example is a little more involved, what's happening is that we have two parts.\n", - "\n", - "The first is the minimum of `10`, `-1`, `4` and `3`:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "min(10, -1, 4, 3)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The second is the maximum of 0 and the result of the first part:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "max(0, -1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is 0, and that's the result.\n", - "\n", - "## Overwriting Functions (!)\n", - "\n", - "One thing that may be surprising if you have worked with other languages is that these functions can be overridden. \n", - "\n", - "#### Step 1. Check the type of `max`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "type(max)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 2. Find the maximum value out of `1, 7, 3, 4, 5`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "max(1, 7, 3, 4, 5) #max(), min() are built-in functions" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 3. Let's assign `max` with `100`\n", - "\n", - "The name `max`, for example, has nothing special about it---it's not a keyword---and the name can be bound to an integer or any other value:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# assign 100 to max. <---- don't do this\n", - "max = 100" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 4. Check the type of `max`\n", - "So now we've done this `max` is an integer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "type(max)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 5. Try to call `max(4, 5)`.\n", - "Then, we'll get a type error since `max` is an integer now, not a function, and you can't call an integer.\n", - "\n", - "- How can we get max() function back?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "max(4, 5)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 6. To recover the `max()` function, use `del` command.\n", - "\n", - "In this case we can remove the local definition of `max` that is masking the built-in function by using the `del` statement:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "del max" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 7. Check it.\n", - "If we check now, we'll see that `max` is back to being a function:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "max(4, 5)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## In-Place Operations\n", - "\n", - "In-place operation of the standard arithmetic operations are possible using `+=`, `-=`, and so forth, but neither pre/postincrement nor pre/post decrement in Python." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "b = 2.5\n", - "b += 0.5 # b = b + 0.5\n", - "b" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## bool - Boolean Data Type\n", - "\n", - "The boolean data type is either `True` or `False`. In Python, boolean variables are defined by the `True` and `False` keywords. Boolean arithmetic is the arithmetic of true and false logic. A boolean or logical value can either be True or False. Boolean values can be manipulated and combined with boolean operators. Boolean operators in Python include `and`, `or`, and `not`. It either returns `True` or `False` according to the condition.\n", - "\n", - "__Boolean operators:__\n", - "\n", - "```\n", - " or\n", - " and\n", - " not\n", - "```\n", - "\n", - "__Comparison Operators:__\n", - "- `>`\tGreater than - True if left operand is greater than the right\t`x > y`\n", - "- `<`\tLess than - True if left operand is less than the right\t`x < y`\n", - "- `==`\tEqual to - True if both operands are equal\t`x == y`\n", - "- `!=`\tNot equal to - True if operands are not equal\t`x != y`\n", - "- `>=`\tGreater than or equal to - True if left operand is greater than or equal to the right\t`x >= y`\n", - "- `<=`\tLess than or equal to - True if left operand is less than or equal to the right\n", - "\n", - "These comparison operators are quite standard. So for example:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Evalueate the result of a boolean expression\n", - "a = 3 > 4\n", - "a" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and see that the type of `q` is now `bool`:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Evaluate p and q and print whetehr or not it is true. \n", - "q = 5 > 10\n", - "p = 5 < 10\n", - "if (q == True):\n", - " print('q is true')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "if (q):\n", - " print('q is true')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Boolean(Logical) Expressions \n", - "A boolean expression (or logical expression) evaluates to one of two states true or false. Comparisons can be combined using the logical operators `and`, `or` and `not`. So for example:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 1: \n", - "\n", - "Write a boolean expression that returns true if `age` is between `20` and `29`, inclusively, false otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "age >= 20 and age <= 29" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 2: Using chained comparison\n", - "\n", - "- One really __slick feature__ of Python's comparisons are chained comparisons:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "20 <= age <= 29" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 3: What is the result of the following expression?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "5 < 10 and 10 < 20" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "5 < 10 or 10 < 20" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "5 < 10 or 10 > 20" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Short-circuit evaluation\n", - "\n", - "Python uses [\"short-circuit\" evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation) of logical expressions if the value of subsequent terms can't affect the result. \n", - "\n", - "\n", - "#### Example 4: " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1 < 0 and max(0, 1, 2) > 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "`False` since the first operand is `False` regrardless of the following part of expression. \n", - "\n", - "There is no way that the full expression could ever evalute to `True` and so Python __skips the evaluation of the second operand__, and returns `False` straight away. This is called short-circuit evaluation." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 5: What do you expect from the following two logical expressions, respectively?\n", - "\n", - "1. `1 > 4 and 5 < xx`\n", - "1. `1 > 4 or 5 < xx`\n", - "\n", - "Possible choices:\n", - "1. Name error\n", - "1. Type error\n", - "1. True \n", - "1. False" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1 > 4 and 5 < xx" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "1 > 4 or 5 < xx" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 6: What is the evaluation of the following expreesion?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = 50\n", - "a < 10 or a > 100" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Python's `or` operator works in a similar way. The short-circuit evaluation works here since the first operand is `True`:\n", - "\n", - "#### Example 7: What is the evaluation of the following expreesion?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "b = 0\n", - "b < 10 or b > yy # second term won't be evaluated" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And finally, the `not` operation inverts the value of the argument:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "not 10 <= a <= 90" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example 8:\n", - "Write a logical expression which evaluates an age to be `True` if the age is a teenage. The teenage means between 13 and 19 inclusively." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "age = 15\n", - "# write a logical expression below to determine whether or not age is teen.\n", - "age >= 13 and age <= 19\n", - "\n", - "13 <= age <= 19" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Exercise 1. Teen Age\n", - "\n", - "- Write a function, `is_teen(age)`, which returns if `age` is a teen age.\n", - "- Write a code to test `is_teen()` while calling it from `age = 9` to `age = 21`.\n", - "- Print the result as shown below:\n", - "\n", - "```\n", - "The age 9 is not a teen\n", - "The age 10 is not a teen\n", - "The age 11 is not a teen\n", - "The age 12 is not a teen\n", - "The age 13 is a teen\n", - "The age 14 is a teen\n", - "The age 15 is a teen\n", - "The age 16 is a teen\n", - "The age 17 is a teen\n", - "The age 18 is a teen\n", - "The age 19 is a teen\n", - "The age 20 is not a teen\n", - "The age 21 is not a teen\n", - "```\n", - "\n", - "#### Step 1: Code is_teean(age) function first" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Replace `None` with the logic expression you developed above.\n", - "def is_teen(age):\n", - " return None " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 2: Write a test code to produce the output shown above.\n", - "\n", - "#### Method 1: Using a list of ages " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# test is_teen() \n", - "for age in [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]:\n", - " if is_teen(age): \n", - " print('The age', age, 'is a teen')\n", - " else:\n", - " print('The age', age, 'is not a teen')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 2: Using `range()` " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "for age in None:\n", - " if is_teen(age): \n", - " print('The age', age, 'is a teen')\n", - " else:\n", - " print('The age', age, 'is not a teen')" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Exercise 2. Leap Year\n", - "\n", - "A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400. For example,\n", - "\n", - "```\n", - "2017 is not a leap year\n", - "1900 is a not leap year\n", - "2012 is a leap year\n", - "2000 is a leap year\n", - "```\n", - "\n", - "To test a leap year interactively, you may code it as shwon below:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Python program to check if the input year is a leap year or not\n", - "year = int(input(\"Enter a year: \"))\n", - "if (year % 4) == 0:\n", - " if (year % 100) == 0:\n", - " if (year % 400) == 0:\n", - " print(\"{0} is a leap year\".format(year))\n", - " else:\n", - " print(\"{0} is not a leap year\".format(year))\n", - " else:\n", - " print(\"{0} is a leap year\".format(year))\n", - "else:\n", - " print(\"{0} is not a leap year\".format(year))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 1: Coding `is_leap_year()` function:\n", - "Now, complete the following `is_leap_year()` function that returns `True` if `year` is a leap year, `False` otherwise. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "def is_leap_year(year):\n", - " return (None and None) or (None) == 0" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Step 2: Coding to test `is_leap_year()` to have the following output shown below:\n", - "```\n", - "100 No, it is not.\n", - "200 No, it is not.\n", - "1990 No, it is not.\n", - "2000 Yes, it is a leap year\n", - "2002 No, it is not.\n", - "2004 Yes, it is a leap year\n", - "2010 No, it is not.\n", - "2100 No, it is not.\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# test leap_year()\n", - "for year in [100, 200, 1990, 2000, 2002, 2004, 2010, 2100]:\n", - " if is_leap_year(year):\n", - " print(year, 'is a leap year')\n", - " else:\n", - " print(year, 'is not a leap year')\n", - " " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "------------------\n", - "\n", - "# Homework \n", - "\n", - "__\"모인활:모두를 위한 인공지능의 활용\"__ 수강생은 다음 문제들 중에서 여러 방법으로 코딩할 수 있는 문제는 단 하나의 방법으로만 코딩해도 됩니다. \n", - "\n", - "## 1. Given an integer number, print its last digit.\n", - "\n", - "Print the last digit of a which is an integer.\n", - "\n", - "For example, print `5` if `35`, `6` if `6`, and `9` if `5679`. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 1: Using any arithmetic operators.\n", - "- Often we use both modulus `%` operator and floor division `//`. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer:\n", - "a = int(input(\"Enter an integer number: \"))\n", - "print(type(a))\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 2: Using `len()` and indexing " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer as a string\n", - "s = input(\"Enter an integer number: \")\n", - "print(type(s))\n", - "# Using len() and indexing \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 3: Using indexing " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer as a string\n", - "s = input(\"Enter an integer number: \")\n", - "print(type(s))\n", - "# using indexing \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 2. Given a three-digit number. Find the sum of its digits.\n", - "\n", - "Print the sum of three-digit number which is an integer.\n", - "\n", - "For example, print `10` if `316`, `13` if `256`, `18` if `567`. \n", - "\n", - "#### Method 1: Using % (mod operator) and // (integer division)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = int(input(\"3 digit number: \"))\n", - "\n", - "\n", - "\n", - "\n", - "print (x + y + z)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "a = int(input(\"3 digit number: \"))\n", - "\n", - "\n", - "\n", - "\n", - "print (x + y + z)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 2: __Sum all digits for any number of digits and using str() and for loop__" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer as a string:\n", - "s = input(\"Enter an int number: \")\n", - "\n", - "# for example, print 6 if a is 123, 18 if a is 369. \n", - "sum = 0\n", - "\n", - "\n", - " \n", - "print(sum)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 3: Using indexing" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer as a string:\n", - "s = input(\"Enter an int number: \")\n", - "\n", - "# for example, print 6 if a is 123, 18 if a is 369. \n", - "sum = 0\n", - "\n", - "\n", - " \n", - "print(sum)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Method 4: Using list comprehension - This topic will be handled later sessions. \n", - "Using built-in function `sum()`, `int()`, and list comprehension, we can just do it in one line of code.\n", - "\n", - "- To use built-in `sum()` function, use `del` command to undefine sum which was previously defined.\n", - "- `Input()` returns a `str` type data. \n", - "- Use list comprehension and get each character.\n", - "- Use `sum()` to sum up the element in the list. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "del sum\n", - "# Read an integer as a string:\n", - "s = input(\"Enter an int number: \")\n", - "\n", - "# for example, print 6 if a is 123, 18 if a is 369. \n", - "total = None\n", - "\n", - "print(total)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "__Challenge Problem:__ Do it for any number of digits and using while loop" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer:\n", - "n = int(input(\"Enter an int number: \"))\n", - "# for example, print 6 if a is 123, 18 if a is 369. \n", - "sum = 0\n", - "\n", - " \n", - "print(sum)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 3. Clock displays military time\n", - "\n", - "The integer N given is the number of minutes that is passed since midnight. Display the hour and minute in military time. The program should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59). For example, if N = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So the program should print 2:30." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer:\n", - "a = int(input())\n", - "print(a)\n", - "# print 3:0 for 180, 7:24 for 444, 18:31 for 1111, 23:59 for 1439 \n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 4. Equal numbers\n", - "\n", - "Given three integers, determine how many of them are equal to each other. The program must print one of these numbers: 3 (if all are the same), 2 (if two of them are equal to each other and the third is different) or 0 (if all numbers are different)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer:\n", - "x = int(input(\"x:\"))\n", - "y = int(input(\"y:\"))\n", - "z = int(input(\"z:\"))\n", - "\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Read an integer:\n", - "x = int(input(\"x:\"))\n", - "y = int(input(\"y:\"))\n", - "z = int(input(\"n:\"))\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "--------\n", - "__The LORD bless you and keep you.__ Numbers 6:24" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.3" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/ipynb/Lec00Overview.ipynb b/ipynb/Lec00Overview.ipynb index f80aa51..51291fe 100644 --- a/ipynb/Lec00Overview.ipynb +++ b/ipynb/Lec00Overview.ipynb @@ -77,9 +77,9 @@ "source": [ "## Getting Python\n", "\n", - "You will be using Python 3.x or latest (not 2.x) throughout the course, including many popular 3rd party Python libraries or modules. There are many ways of installing Python. \n", + "You will be using Python 3.6 or latest (not 2.x) throughout the course, including many popular 3rd party Python libraries or modules. There are many ways of installing Python. \n", "\n", - "For the program development environment, you may use any kind of IDE. Personally, I have reviewed or used a few IDE’s such as Anaconda, Canopy, Eclipse, and PyCharm. At this point I ended up using [Anaconda](http://continuum.io/downloads) and 64 bit Python executable. It comes with an easy-to-install bundle of Python and 3rd party libraries. \n", + "For the program development environment, you may use any kind of IDE. Personally, I have reviewed or used a few IDE’s such as Anaconda, Canopy, Eclipse, and PyCharm. At this point I ended up using [Anaconda](http://continuum.io/downloads) and 64 bit Python executable since my computer is 64-bit system. It comes with an easy-to-install bundle of Python and 3rd party libraries. \n", "\n", "In this first class, we will be using a variety of data types of Python and understand the basic concepts of the language to ensure everything goes smoothly moving forward, While some of this will likely be dull, doing it now will enable us to do more exciting work in the days that follow without getting bogged down in further software development. It is essential that you complete it timely. \n" ] @@ -109,23 +109,8 @@ "5. Capstone: Retrieving, Processing, and Visualizing Data with Python\n", "\n", "In this specialization, I expect you are to finish 4 out of 5 parts.\n", - "I hope that you take this course along with a Certification specialized in Python.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## MOOC Pye4 Lessons for 모인활(AI Applications for All) Class\n", - "Every student is expected to go through the the following topics on [PY4E online lessons](https://www.py4e.com/lessons). Submit the screen capture of the final grade on Piazza by the end of 7th week of this semeter. You may check [the due date](https://piazza.com/class/k7222vwq8y61ni) for each lesson in Piazza.\n", - "\n", - " 2. Why Program?\n", - " 3. Variables, expression and statement\n", - " 4. Conditional Execution\n", - " 5. Function\n", - " 6. Loops and Iterations\n", - " 7. Strings\n", - " 9. Lists" + "I hope that you take this course along with a Certification specialized in Python.\n", + "\n" ] }, { @@ -181,10 +166,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Tutorial for Jupyter Notebook\n", - "- In-depth [video by developer](https://www.youtube.com/watch?v=XFw1JVXKJss) by its creator, Fernando Perez, in PyCon 2014 \n", - "- [Introductory Video by SimpiLearn](https://www.youtube.com/watch?v=3C9E2yPBw7s)\n", - "- It is a must to watch!" + "## Video tutorial for Jupyter Notebook\n", + "- Look for ones in you-tube.\n", + "- In-depth [video](https://www.youtube.com/watch?v=XFw1JVXKJss) by its creator, Fernando Perez, in PyCon 2014 \n", + "- It is a must to watch!\n" ] }, { @@ -207,12 +192,12 @@ "metadata": {}, "source": [ "# Code cell or Markdown cell\n", - "Jupyter Notebook consists of a series of so-called cells. There are two types of cells that contains either code or document. Cells that contains code is called __code cell__, whereas cell that contains document is called __markdown cell__. \n", - "\n", - "By default, the notebook creates a code cell. Let's explore working with code cells. You may convert a code cell into a markdown cell by typing a short-cut ``, `` vice versa. \n", + "IPython Notebook consists of a series of so-called cells. There are two types of cells that contains either code or document. Cells that contains code is called code cell, whereas cell that contains document is called markdown cell. By default, the notebook creates a code cell. Let's explore working with code cells.\n", "\n", "## Code cells\n", - "May contain python code and ipython magic." + "May contain python code and ipython magic.\n", + "\n", + "\n" ] }, { @@ -235,8 +220,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Running Cells\n", - "Jupyter notebook cell is capable of running code in a wide range of languages. However, the default kernel in Jupyter notebook runs Python code. If the cell is a markdown cell, it just randers into webpage. \n", + "# Running Code\n", + "IPython is capable of running code in a wide range of languages. However, this notebook, and the default kernel in IPython, runs Python code. If the cell is a markdown cell, it just randers into webpage. \n", "\n", "Run a cell using `````` or \"Run Cell\" button in the toolbar above:\n", "\n", @@ -250,18 +235,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Running OS or cell magic commands in code cell\n", - "\n", - "- Use `%` to run the OS command. (Some people prefer to using ! instead of %.)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 1. Print the current folder name (present working directory).\n", - "- Try it with `%pwd` and `%dir`\n", - "- `pwd` means `present working directory` or `print working directory`." + "Run a command `pwd`. `pwd` means `present working directory` or `print working directory`." ] }, { @@ -275,8 +249,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### 2. Print the list of files in the current folder.\n", - "- Try it with `%ls` and `%dir`" + "list file names in a current folder" ] }, { @@ -290,8 +263,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### 3. Print the contents of a file. \n", - "- Try it with `%cat ` and `%type `" + "Run a command `!cat [filename]` that prints the contents the file. Use `!` to run the OS command." ] }, { @@ -305,8 +277,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Running Python code in code cell\n", - "\n", "## Arithmetic\n", "Let's start simple with some arithmetic..." ] @@ -430,7 +400,10 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "print('What is your name?')\n", + "# your code here\n" + ] }, { "cell_type": "markdown", @@ -451,16 +424,18 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "print('What is your age?')\n", + "# your code here\n" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## List\n", - "Python makes it easy to create lists, which can contain any kind of object. We can index these, concatenate them, and find the length, just as we can with strings. For more examples, refter to [Python Tutorials](https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehension#more-on-lists)\n", + "## Function\n", "\n", - "#### 1. Create two lists, one with raibow colors and the other with a few prime numbers:" + "Define a function if you are using the same set of code more than once. Be careful when using `:` and `` characters." ] }, { @@ -469,15 +444,49 @@ "metadata": {}, "outputs": [], "source": [ - "colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']\n", - "primes = [2, 3, 5, 7, 11, 13]" + "def SayHello(): \n", + " name = input('What is your name?') \n", + " print('Hello ' + name)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "SayHello()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 2. Make a new list called `mixed` by adding two lists ." + "## Writing a code cell into a file \n", + "\n", + "You may use __%%writefile__ cell magic command. You have to place the command at the very first line of the code cell.\n", + "```\n", + "%%writefile mycode.py\n", + "```\n", + "\n", + "\n", + "## Loading external codes\n", + "\n", + "- Drag and drop a .py in the dashboard\n", + "- Use __%load__ with any local or remote url: the Matplotlib Gallery http://matplotlib.org/gallery.html\n", + "\n", + "```\n", + "%%load mycode.py\n", + "```\n", + "\n", + "In this notebook we've kept the output saved so you can see the result, but you should run the next cell yourself (with an active internet connection)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reading a web page\n" ] }, { @@ -485,13 +494,17 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "import requests \n", + "response = requests.get('http://www.handong.edu') # http://www.mit.edu\n", + "response.ok" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 3. How many elements are in the `mixed`?" + "Display the first 1000 characters from the response. Use `response.text[1000]`" ] }, { @@ -505,7 +518,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### 4. What are the first and last elements in the `mixed`?" + "## Read a remote file and process the text" ] }, { @@ -513,20 +526,26 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "from urllib.request import urlopen \n", + "#book = urlopen('http://www.gutenberg.org/cache/epub/10/pg10.txt')\n", + "book = urlopen('http://composingprograms.com/shakespeare.txt')" + ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "wlist = book.read().decode().split()" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 5. Append the next prime number (17) at the end of the `mixed`.\n" + "- Get the number of words in `wlist`" ] }, { @@ -540,7 +559,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Reading a web page\n" + "- Check the first 20 words in `wlist`" ] }, { @@ -548,17 +567,13 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [ - "import requests \n", - "response = requests.get('http://www.handong.edu') \n", - "response.ok" - ] + "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Display the first 1000 characters from the response. Use `response.text[1000]`" + "- Sort words in `wlist`. Use `sort()`." ] }, { @@ -566,15 +581,13 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [ - "response.text[:500]" - ] + "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Read a remote file and process the text" + "- Check the first 10 words in `wlist` after sort(). Use `count()`." ] }, { @@ -582,17 +595,13 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [ - "from urllib.request import urlopen \n", - "book = urlopen('http://www.gutenberg.org/cache/epub/10/pg10.txt')\n", - "#book = urlopen('http://composingprograms.com/shakespeare.txt')" - ] + "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 1. Make a list words out of the book read from url." + "- Count a specific word `truth` in `wlist`." ] }, { @@ -601,14 +610,14 @@ "metadata": {}, "outputs": [], "source": [ - "wlist = book.read().decode().split()" + "wlist.count('truth')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 2. Get the number of words in `wlist`" + "Remove duplicated words and check its length(or number of words). Use `set()`." ] }, { @@ -618,11 +627,20 @@ "outputs": [], "source": [] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ulist[:10] # set is not subscriptable" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 3. Check the first 10 words in `wlist`" + "- Convert `ulist` in `set` type to `list` type." ] }, { @@ -630,16 +648,17 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "wlist = list(ulist) \n", + "len(wlist)" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 4. Sort words in `wlist`. \n", - "\n", - "- Use the list's method called `sort()`\n", - "- To find methods available, Use after the class/variable name" + "- Sort first\n", + "- Then print the first and last 10 words in the list, respectively." ] }, { @@ -649,13 +668,6 @@ "outputs": [], "source": [] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 5. Check the first 10 words in `wlist` after `sort()`." - ] - }, { "cell_type": "code", "execution_count": null, @@ -667,7 +679,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### 6. Count a specific word `truth` in `wlist` or the Bible." + "- Get the last word in alphabetical order" ] }, { @@ -681,9 +693,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### 7. Remove duplicated words and check its length(or number of words). \n", - "- Use `set()` function returns unique elements in a set type which is unordered or a kind of bag.\n", - "- Therefore, the set data type does not support indexing." + "- Get the longest word. Use `max() with key=len` argument." ] }, { @@ -699,15 +709,20 @@ "metadata": {}, "outputs": [], "source": [ - " ulist[:10] # set is not subscriptable; read the error message" + "alist = [] \n", + "for w in wlist: \n", + " if len(w) == 6 and w[::-1] in wlist: \n", + " alist.append(w) \n", + "print(alist)\n" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "#### 8. Convert a set data type object into a list type and sort elements in it.\n", - "- Use list() function to convert a set object to a list object." + "[w for w in wlist if w[::-1] in wlist and len(w) == 6]" ] }, { @@ -715,15 +730,16 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "[w for w in wlist if w[::-1] in wlist and len(w) > 6 ]" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 9. Find the last word in alphabetical order in the word list.\n", - "- sort the list first. \n", - "- print last 10 words in the list." + "## List\n", + "Python makes it easy to create lists, which can contain any kind of object. We can index these, concatenate them, and find the length, just as we can with strings. For more examples, refter to [Python Tutorials](https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehension#more-on-lists)" ] }, { @@ -731,28 +747,36 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "lst = [1, 2.0, 3, 'handong']\n", + "lst" + ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "lst + lst" + ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "lst[0]" + ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "#### 10. Find the longest word in the book.\n", - "- Use `max()` function with `key=len` argument." + "lst[-1]" ] }, { @@ -760,23 +784,15 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "len(lst)" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 11. Find emornilap in the book.\n", - "\n", - "#### What's an Emordnilap?\n", - "\n", - "Emordnilaps are like palindromes' evil twins. Instead of being the same word, these rare words make a different real word when spelled backward! Reverse the word \"stop\" and it becomes \"pots.\" Flip \"drawer\" and you get \"reward.\" English contains a surprising variety of words that change meanings as soon as you read them right to left.\n", - "\n", - "Emordnilap Examples: \n", - " - desserts and stressed, \n", - " - decaf and faced\n", - " - edit and tide\n", - " - deeps and speed" + "We can also append new things to the end of an existing list." ] }, { @@ -784,13 +800,17 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "lst.append('song')\n", + "lst" + ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### a pythonic way - using list comprehension" + "## Set\n", + "Python also provides the __set__ data structure, which can be created using curly brackets." ] }, { @@ -798,31 +818,19 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, "source": [ - "## Functions\n", - "\n", - "Now let's take a look at defining and using functions in Python. We will start by defining a function to evaluate a polynomial." + "a = {1, 2, 3, 4}\n", + "a" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "#### Defining your own function\n", - "\n", - "- Define a function if you are using the same set of code more than once. \n", - "- Be careful when using `:` and `` characters.\n", - "\n", - "\n", - "#### 1. Do the following task three times: \n", - "`\n", - "Ask a name to a person and say 'Hello` to him/her. . \n", - "`" + "b = {2, 3, 4, 5}\n", + "b" ] }, { @@ -830,20 +838,27 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "a.add(1)\n", + "a" + ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "a & b" + ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "#### 2. Draw a linear graph ` y = x ` or `x = 1, 2, 3, 4 and y = 1, 2, 3, 4`" + "a | b" ] }, { @@ -852,20 +867,22 @@ "metadata": {}, "outputs": [], "source": [ - "import matplotlib.pyplot as plt\n", - "%matplotlib inline\n", - "\n", - "plt.plot(None, None)\n", - "plt.show()" + "a ^ b" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [] + }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 3. Plot a polynomial from `x = -10` and `x = 10 `.\n", - "- Its coefficients are `a = 1, b = 2, c = 3`\n", - "- Define a polynomial, ` y = a * x^^2 + b * x + c ` that returns` y`. " + "## Image & Video Display\n", + "\n", + "The pictures and more exotic objects can also be displayed, as long as their representation supports the IPython display protocol.\n", + "For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):" ] }, { @@ -874,30 +891,34 @@ "metadata": {}, "outputs": [], "source": [ - "def poly(x, a, b, c):\n", - " None\n", - " return None" + "import matplotlib.pyplot as plt\n", + "from matplotlib.image import imread\n", + "\n", + "img = imread('https://github.com/idebtor/KMOOC-ML/blob/master/ipynb/images/lenna.png?raw=true')\n", + "plt.imshow(img)\n", + "plt.show()" ] }, { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "scrolled": true + }, "outputs": [], "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plot\n", - "%matplotlib inline\n", - "\n", - "x = None\n", - "plt.plot(None, None)" + "from IPython.display import Video\n", + "#Video(\"https://github.com/idebtor/KOICA-Python/tree/master/videos/MLwithPythonIntro.mp4\")\n", + "Video(\"videos/MLwithPythonIntro.mp4\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### 4. Draw `cos(x)` function from `x = 0` and `x = 2 * pi`." + "## Functions\n", + "\n", + "Now let's take a look at defining and using functions in Python. We will start by defining a function to evaluate a polynomial." ] }, { @@ -906,18 +927,22 @@ "metadata": {}, "outputs": [], "source": [ - "x = np.arange(0, 2 * np.pi, 0.1)\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", + "\n", + "x = np.arange(0, 6, 0.1)\n", "plt.plot(x, np.cos(x))\n", "plt.show()" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## Image Display\n", - "\n", - "The pictures and more exotic objects can also be displayed, as long as their representation supports the IPython display protocol." + "# how do you evaluate x?\n" ] }, { @@ -926,26 +951,26 @@ "metadata": {}, "outputs": [], "source": [ - "from matplotlib.image import imread\n", - "#%matplotlib notebook \n", - "\n", - "img = imread('https://github.com/idebtor/KMOOC-ML/blob/master/ipynb/images/lenna.png?raw=true')\n", - "plt.None" + "def poly(x, a, b, c):\n", + " y = a*x**2 + b*x + c\n", + " return y" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## Class and Object" + "x = 1\n", + "poly(x, 1, 2, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now lets create a class. In Python, every class should derive from object. Our class will describe a person, with a name and an age. We will supply a constructor, and a method to get the full name.\n", - "- How to create a class: Refer to [Wikibook](http://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes)" + "We can also pass an array as the argument x." ] }, { @@ -954,21 +979,17 @@ "metadata": {}, "outputs": [], "source": [ - "class Person(object):\n", - " def __init__(self, first, last, age):\n", - " self.first = first\n", - " self.last = last\n", - " self.age = age\n", - " \n", - " def full_name(self):\n", - " return self.first + ' ' + self.last" + "#from numpy import array\n", + "import numpy as np\n", + "x = np.arange(0, 6, 0.1)\n", + "poly(x, 1, 2, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Now we can create an instance of a Person, and work with the attributes of the class." + "And also do this for a 10-element array, and quickly make a plot of the values." ] }, { @@ -977,8 +998,18 @@ "metadata": {}, "outputs": [], "source": [ - "person = Person('Lee', 'Handong', 21)\n", - "person.first" + "%matplotlib inline\n", + "import matplotlib.pyplot as plot\n", + "\n", + "x = np.arange(10)\n", + "plot.plot(x, poly(x, 2, 3, 4))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also specify keyword arguments, which are specified by name." ] }, { @@ -987,7 +1018,9 @@ "metadata": {}, "outputs": [], "source": [ - "person.last" + "def poly(x, a=1, b=2, c=3):\n", + " y = a*x**2 + b*x + c\n", + " return y" ] }, { @@ -996,7 +1029,7 @@ "metadata": {}, "outputs": [], "source": [ - "person.full_name()" + "poly(x)" ] }, { @@ -1005,14 +1038,22 @@ "metadata": {}, "outputs": [], "source": [ - "person.last = 'Kim'" + "poly(x, b=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "In Python, we can add new class attributes on the fly, even if they have not been defined yet." + "## Class and Object" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now lets create a class. In Python, every class should derive from object. Our class will describe a person, with a name and an age. We will supply a constructor, and a method to get the full name.\n", + "- How to create a class: Refer to [Wikibook](http://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Classes)" ] }, { @@ -1021,183 +1062,96 @@ "metadata": {}, "outputs": [], "source": [ - "person.smoke = False\n", - "person.smoke" + "class Person(object):\n", + " def __init__(self, first, last, age):\n", + " self.first = first\n", + " self.last = last\n", + " self.age = age\n", + " \n", + " def full_name(self):\n", + " return self.first + ' ' + self.last" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Writing a code cell into a file \n", - "\n", - "You may use __%%writefile__ cell magic command. You have to place the command at the very first line of the code cell.\n", - "```\n", - "%%writefile mycode.py\n", - "```\n", - "\n", - "\n", - "## Loading external codes\n", - "\n", - "- Drag and drop a .py in the dashboard\n", - "- Use __%load__ with any local or remote url: the Matplotlib Gallery http://matplotlib.org/gallery.html\n", - "\n", - "```\n", - "%load mycode.py\n", - "```\n", - "\n", - "In this notebook we've kept the output saved so you can see the result, but you should run the next cell yourself (with an active internet connection).\n", - "\n", - "----------" + "Now we can create an instance of a Person, and work with the attributes of the class." ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "## Markdown Summary \n", - "Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown. Mostly, Markdown is just regular text with a few non-alphabetic characters thrown in, like # or *.\n", - "\n", - "      __Desired style__      __in Markdown syntax__      __in HTML syntax__\n", - "```\n", - "Heading 1\t # Title

Title

\n", - "Heading 2\t ## Title

Title

\n", - "Heading 3\t ### Title

Title

\n", - "Heading 4\t #### Title

Title

\n", - "\n", - "Paragraph Just start typing

Just start typing

\n", - " \n", - "Bold **Text** Text\n", - "Italic *Text* Text\n", - "Strike ~~Text~~ Text\n", - " \n", - "List (unordered) * List item 1

  • List item 1
  • \n", - " * List item 2
  • List item 2
  • \n", - " * List item 3
  • List item 3
\n", - "\n", - "List (ordered) 1. List item 1
  • List item 1
  • \n", - " 1. List item 2
  • List item 2
  • \n", - " 1. List item 3
  • List item 3
\n", - "\n", - "Images\t ![Alt text](path/image.jpg)\t \"Alt\n", - "Hyperlinks\t[Link text](https://kmooc.kr/)\tLink text\n", - "\n", - "Quoted (indent) > Text

Text

\n", - "Code (inline) ``Statement`` Statement\n", - "Code (fenced)\t ```
Statement   \n",
-    "                  Statement 1               1Statement\n",
-    "                  Statement 2               2Statement\n",
-    "                  Statement 3               3
\n", - " ``` \\\n", - "``` " + "person = Person('Lee', 'Handong', 21)\n", + "person.first" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "# Examples: Markdown in action" + "person.last" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "# Title\t- Heading 1\t\n", - "## Title - Heading 2\n", - "### Title - Heading 3\n", - "#### Title - Heading 4\t" + "person.full_name()" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "**Bold Text**   __another bold text__ \n", - "*Italic Text*   _another italic text__ \n", - "~~Text~~ " + "person.last = 'Kim'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "* unordered list\n", - "* apple\n", - "* orange\n", - "- ANOTHER unordered list\n", - "- apple\n", - "- orange\n", - "\n", - "\n", - "1. ordered list\n", - "2. second\n", - "3. third" + "In Python, we can add new class attributes on the fly, even if they have not been defined yet." ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "[Welcome to Handong Global University](https://www.handong.edu)\n", - "\n", - "\n", - "
그림 3: 숫자 인식 인공 신경망
" + "person.smoke = False\n", + "person.smoke" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "That gives you a quick tour of the capabilities of IPython. \n", "\n", - "``` \n", - "This is a quote.\n", - "\n", - "# Title\t- Heading 1\t\n", - "## Title - Heading 2\n", - "### Title - Heading 3\n", - "#### Title - Heading 4\t\n", - "```\n", - "\n", - "> This is block quote \n", - ">\n", - "> God is good all the time. \n", - "> All the time God is good. \n", - "> (There are two hidden spaces after \"all the time.\" and \"God is good.\" that makes a new line.\n", - "> Otherwise, it will display two line into one like these two sentences.)\n", - "\n", - "\n", - "`-----------` This draws a following line. \n", - "\n", - "-------\n" + "We covered a lot of ground here, but this should give you an idea of the power that Python puts at your fingertips. In the later lectures, we will give you a more in-depth tour of most of these features." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## LaTex \n", - "\n", - "LaTeX is a high-quality typesetting system; it includes features designed for the production of technical and scientific documentation. LaTeX is the de facto standard for the communication and publication of scientific documents. LaTeX is available as free software.\n", - "\n", - "For example:\n", + "# Tips on Jupyter Notebook\n", "\n", - "$$ D = \\sqrt{b^2 + 4ac} $$\n", + "__When you execute code somewhere in the middle of a notebook, the code fragment may be dependent on imports, intermediate results in local variables and other such initializations in preceding cells. So it is better to execute code cells sequentially, starting at the top, when new to IPython Notebook, to avoid being confused by such extraneous errors.__ \n", "\n", - "\\begin{align}\n", - "z = w_0x_0 + w_1x_1 + ... + w_m x_m = \\sum_{j=0}^{m} x_j w_j = \\mathbf{w^Tx}\n", - "\\end{align}\n", + "Even so if you want to dive in and not have to execute each preceding code cell then you'll need to execute the menu item 'Cell->Run All'. This executes each code cell for you sequentially once, so from that point on all dependencies on prior code cells are satisfied.\n", "\n", - "$ D = \\sqrt{b^2 + 4ac}$ \\\n", - "$ z = w_0x_0 + w_1x_1 + ... + w_m x_m = \\sum_{j=0}^{m} x_j w_j = \\mathbf{w^Tx} $\n", - "\n", - "---------" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ "# A simple way to start Jupyter notebook in Windows\n", "To start an Jupyter Notebook, you create a console window first, then you type \"jupyter notebook\" and options in the command-line prompt. Then you still need to navigate to file folders where your Jupyter Notebook files(~.ipynb) are. It is cumbersome. \n", "\n", @@ -1213,21 +1167,6 @@ "```\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Closing and Tips on Jupyter Notebook\n", - "\n", - "That gives you a quick tour of the capabilities of Jupyter notebook or IPython. \n", - "\n", - "We covered a lot of ground here, but this should give you an idea of the power that Python puts at your fingertips. In the later lectures, we will give you a more in-depth tour of most of these features.\n", - "\n", - "When you execute code somewhere in the middle of a notebook, the code fragment may be dependent on imports, intermediate results in local variables and other such initializations in preceding cells. So it is better to execute code cells sequentially, starting at the top, when new to IPython Notebook, to avoid being confused by such extraneous errors.__ \n", - "\n", - "Even so if you want to dive in and not have to execute each preceding code cell then you'll need to execute the menu item 'Cell->Run All'. This executes each code cell for you sequentially once, so from that point on all dependencies on prior code cells are satisfied." - ] - }, { "cell_type": "markdown", "metadata": {},