Tag Archives: Python

Pizza price calculation | 计算披萨价钱🍕

Many of us are still in coronavirus lockdown. We are very proud of all of you for staying healthy and safe.😀

In today’s google classroom, we ordered some pizza for lunch. 🍕  We made a Python program to calculate 👩‍💻 which pizza size gives us the best value.

Our goal: to find the lowest price per bite.  To get that, we divide cost by size.

def pizzaBitePrice(radius,price):
    area=radius**2*3.14
    unit_price = price/area
    return(unit_price)
# small pizza
pizzaBitePrice(7,12)
0.07799298063174313
# medium pizza
pizzaBitePrice(8,14.75)
0.06593351910828026
# large pizza
pizzaBitePrice(9,14.75)
0.057993237398757565

👍The conclusion is: the large size one gives us the best value with price of 5.7 cents (plus tax) per bite.

Welcome to our New Google Classroom!!😃

Hello everybody!😃 Welcome back to Magic Math Mandarin.  Since we are staying home because of covid-19, we brought our classes to google classroom so our students can keep on learning even during this pandemic👩‍🏫. Now we can all communicate with each other online💻. In this classroom we will be learning Chinese🈷, math➗, and programming👩‍💻. Our teachers will put new assignments everyday about each topic.  If you would also like to join our wonderful classrooms then here is the class code mtxl6j4

Remember to stay home and don’t get sick!😷 Please join our classroom today!👍💖

 

Ipython Shell Keyboard shortcuts 键盘快捷键 (Kuàijié jiàn)

In this past weekend’s coding class we practice keyboard ⌨ shortcuts in the interactive Python shell (Ipython).

Since most of the students are learning typing ⌨, practicing these keyboard shortcuts actually help them learn typing by reinforcing memory of where the keys are.

The keyboard shortcuts allows you to minimize finger movements on the keyboard, which means you don’t even have to lift your hand ✋ for the “Backspace”, ‘Home’, ‘End’ or arrow keys (most of the time).    Spend 15 minutes per day practicing these.  Pretty soon, you will be a fast coder.

🚕Navigation

keystroke Action
Ctrl-a Move cursor to the beginning of the line
Ctrl-e Move cursor to the end of the line
Ctrl-b or the left arrow key Move cursor back one character
Ctrl-f or the right arrow key Move cursor forward one character

👦Text Entry

Keystroke Action
Backspace key Delete previous character in line
Ctrl-d Delete next character in line
Ctrl-k Cut text from cursor to end of line
Ctrl-u Cut text from beginning of line to cursor
Ctrl-y Yank (i.e. paste) text that was previously cut
Ctrl-t Transpose (i.e., switch) previous two characters

🐞Command History

Keystroke Action
Ctrl-p (or the up arrow key) Access previous command in history
Ctrl-n (or the down arrow key) Access next command in history
Ctrl-r Reverse-search through command history

🐳Miscellaneous

Keystroke Action
Ctrl-l Clear terminal screen
Ctrl-c Interrupt current Python command
Ctrl-d Exit IPython session

The shortcuts are referenced from  Python Data Science Handbook.   As its author Jake Vanderplas says, these shortcuts are not inherent in Ipython shell itself, but are based on GNU Readline library.

Our cofounder’s new book release

We are really proud of our co-founder(联合创始人 lián hé chuàng shǐ rén), Sarah Chen, for her new book release, which is now public.   Congratulations!

Her book is available in various outlets:

Here is her pre-release announcement on LinkedIn in July this year.

 

 

argmax, argmin argsort and quick sort | 快速排序

This Saturday class we went over indexing and ordering a group of items by their sorted indices. For those who are more advanced, please go over the section on quick sort.

For example,

>> import numpy as np
>>> packpack =np.array([‘snack’,’book’,’pen’,’eraser’,’apple’])
# Position of the biggest word (alphabetically)
>>> np.argmax(packpack)

[out]: 0
# Position of the smallest word (alphabetically)
>>> np.argmin(packpack)

[out]: 4

# Position of the words if we are to sort them alphabetically
>>> np.argsort(packpack)

[out]: array([4, 1, 3, 2, 0], dtype=int64)

Now let us sort them:
>>> packpack[np.argsort(packpack)]

[out]: array([‘apple’, ‘book’, ‘eraser’, ‘pen’, ‘snack’], dtype='<U6′)

Then we tried sorting numbers:

numbers = np.array([2,3,5,7,1,4,6,15,5,2,7,9,10,15,9,17,12])
>>> numbers[np.argsort(numbers)]

[out]: array([ 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 9, 9, 10, 12, 15, 15, 17])


Finally we dig deeper: how do you really sort things fast systematically? Using quick sort!

def quick_sort(data):
    """快速排序"""
    if len(data) >= 2:  # 递归入口及出口
        mid = data[len(data)//2]  # 选取基准值,也可以选取第一个或最后一个元素
        left, right = [], []  # 定义基准值左右两侧的列表
        data.remove(mid)  # 从原始数组中移除基准值
        for num in data:
            if num >= mid:
                right.append(num)
            else:
                left.append(num)
        return quick_sort(left) + [mid] + quick_sort(right)
    else:
        return data
numbers= [2,3,5,7,1,4,6,15,5,2,7,9,10,15,9,17,12]
Backpack = ['snack','book','pen','eraser','apple']
print(quick_sort(Backpack))
print(quick_sort(numbers))

 

Saving Ipython script history

%save sessionName linesToKeep

This will save script in line numbers you specify in linesToKeep,for example, 1-20 34-50 64 into a file called “sessionName.py” in your current working directory.

If you are not so specific on which lines you want to keep, you can save everything.

%save sessionName ~0/

This saves everything from the current session, denoted as “~0″ into file “sessionName.py” in your cwd (current working directory).

%save pastSession ~1/

This saves everything from the past session, denoted as “~1” into file “pastSession.py” in your cwd.

tensorflow upgrade and testing | tensorflow 升级和测试

It has been over a year since I last used tensorflow. Not only library versions have changed, but also the syntax. My old jupyter notebook was throwing errors all over the place this morning. It is time to update everything.

For tensorflow, I am using Python 3.6.3 (I used to use Python 3.5), and numpy 1.16.1. TensorFlow has a few dependencies. numpy is one of them. Note the mnist dataset has 70,000 images.

python -c ‘import tensorflow as tf; print(tf.__version__)

(more…)

An great collection of Python notebooks | Python 笔记本集

Here is a really great collection of Python notebooks with lots and lots of links.  We start with some appetizers:

But there are so many and so much more!  You can find them from this page:

Mathematics

    • Linear algebra with Cython. A tutorial that styles the notebook differently to show that you can produce high-quality typography online with the Notebook. By Carl Vogel.

(more…)

Python Data Types | Python 数据类型

Python type NumPy type pandas dtype Usage
str string_, unicode_ object Text
int int_, int8, int16, int32, int64, uint8, uint16, uint32, uint64 int64 Integer numbers
float float_, float16, float32, float64 float64 Floating point numbers
bool bool_ bool True/False values
datetime64[ns] datetime64 Date and time values
timedelta[ns] Differences between two datetimes
category Finite list of text values

Note that what is “str” in Python is called “object” in pandas. This is a potential source of confusion (isn’t everything in Python an object?).

error: Content is protected !!