Python beginners publish web applications using machine learning [Part 2] Introduction to explosive Python !!

Purpose of this article

Tomi, an obstetrician and gynecologist Article by Dr. ["[Self-study] Learning roadmap for machine learning for Python beginners"](https://obgynai. I tried to create my own roadmap by referring to com / self-study-python-machine-learning /).

This article is the second in a group of memo articles. The article is subdivided for readability first! (After writing, I will publish an article that summarizes everything.) (For reference, I have recorded the date and time when I worked on each section.)

Self-introduction

My name is Tsuba Mukku. After graduating from Kyushu University, I re-entered the Department of Medicine, National University School of Medicine. While aiming to graduate from the Faculty of Medicine and pass the National Examination for Medical Practitioners, I am also biting into pure mathematics and computer science (I also take classes in mathematics and information science).

Hand-held skills ・ Competitive Programming ・ "Gityu b" (hps: // Gityu b. This m / Tsubamuku)

Assumed reader

  1. Those who have Progate completion level programming skills

  2. Those who want to try "Learning Roadmap for Machine Learning for Python Beginners"

  3. AtCoder for brown coder and above

Notes

・ Become a researcher who uses "machine learning" on a daily basis ... It is not an article.

・ This time, I am publishing while adding little by little. Some are unfinished. Please pardon.

This goal

My goal this time was to copy all the code in Learning Roadmap for Python Beginners and solve all the exercises on my own.

Record of efforts

1 About numerical values and character strings (learning time: 2020/06/04 13:00)

Note the following in Python: -In Python division, the decimal point is displayed (ex. 6/2 = 3.0)

・ 6/5 and 6 // 5 have different meanings (6/5 = 1.2, 6 // 5 = 1)

-Conversion to decimal number When converting an octal number to a decimal number, multiply it by 0o (o) . Conversely, when converting a decimal number to an octagonal number, write oct (numerical number). If you remember Octopus ,, you should be convinced to write oct.

・ If you want to know the number of digits, write len (str (numerical value)).

2 Variables / logical values / operators

In my case, I had already learned cpp, so there was nothing new to learn. (I think studying is the act of learning what you don't know or can't do)

3 Basics of functions

・ Because there are some differences from cpp, let's study hard.


#Please enter your name on the screen
name = input("Please enter your name")

#Input data()Note that is a str type
age = 3
age += 1

#Show my name and next year's age
print("My name is " + name + " and next year I will be " + str(age) + " years old.")

4 About objects and methods

I was studying this when I bite into cpp and Java, so I learned it easily.

Honestly, if you're not in a state "just before you have a coding interview" about object-oriented objects, you should know something softly (you shouldn't put any effort into it).

Here are some useful methods:

・ Lower (), upper () methods

# lower()The method is,Convert uppercase letters to lowercase letters (mercilessly)
s = "SHINJUKU"
s = s.lower()
print(s) #Output as shinjuku

# upper()The method is,Convert lowercase letters to uppercase (mercilessly)
s = "shibuya"
s = s.upper()
print(s) #Displayed as SHIBUYA

-Find () method

s = 'shinjuku ichome'

print(s.find('a')) #If the character does not exist-1 is returned
print(s.find('s')) #0th exists
print(s.find('u')) #The first to appear is the fifth

・ Count () method

s = 'shinjuku ichome'

print(s.count('u')) #2 pieces
print(s.count('a')) #0 pieces

・ Strip () method (I first learned about it !!) Trimming refers to the operation of removing blank spaces and line breaks. (This is an operation you see in Uva online judges issues)

s = '   shinjuku       ichome      '

s = s.strip()
print(s) #Whitespace between shinjuku ichome is not removed

5 Control syntax / basics of conditional branching

In my case, I had already learned cpp, so there was nothing new to learn. I feel that it is easier to fix basic matters such as if statements if you solve the problem suddenly. I tried to solve the problem immediately.

Exercise 1: Calculate the tax-included price considering the shipping fee

Sample answer
price_without_tax = int(input("Please enter price before tax.")
tax = 1.1 #Constants should basically be prepared as variables
price_with_tax = int(price_without_tax * tax)

if price_with_tax >= 2000:
    print("Delivery fee is free of charge.")
else:
    print("Delivery fee is 350 yen.")
    price_with_tax += 350
    
print("Price including delivery fee is " price_with_tax " yen.")

Exercise 2: Judging pass / fail from test scores

Sample answer
math = int(input("math"))
eng = int(input("eng"))

if math >= 75:
    print("pass")
else:
    print("fail")
    
if eng >= 60:
    print("pass")
else:
    print("fail")

6 How to use the while statement

In my case, I skipped it because I have already learned cpp.

How to use 7 for statement (learning time: 2020/06/04 16:08)

I've worked on this section altogether because the Python for statement is unique.

For example, let's write a program that displays numbers from 0 to 10:

Sample answer cpp
#include <iostream>
using namespace std;
int main(void){
    
    for (int i = 0; i < 21; i++) cout << i << endl;
}

Sample answer Python
for i in range(21): #Handles numbers between 0 and 21 "less than"
    print(i)

Let's change the start value to something other than 0:

Change the start value to something other than 0

for i in range(1,20): #Values between 1 and less than "20" are eligible
    print(i)

Let's change the loop increment:

Change the loop increment
for i in range(1,20,2): #Values between 1 and less than "20" are eligible
    print(i)

I don't understand the problem. .. .. .. .. sad. .. .. .. (If it's cpp, I can afford it ...) (Holded once)

8 Add the entered values to find the average value of the input values at a certain point (learning time: 2020/06/04 19:02)

I tried to tackle the challenge:

Sample answer Python
total_sum = 0
total_person = 0
while True:
    money = int(input("Please enter your money: "))
    total_person += 1
    
    if money == 0:
        break
    else:
        total_sum += money

average_money = total_sum / total_person
print("The average amount of money you have is",average_money,"It's a yen")

9 Summary of how to use list [Part 1](Learning time: 2020/06/04 19:12)

-Convert from tuple to list

tuple_samp = (5,6,7,8)
print(type(tuple_samp)) # <class 'tuple'>


list_samp = list(tuple_samp)
print(type(list_samp)) # <class 'list'>
print(list_samp) # [5, 6, 7, 8]

range_samp = range(5)
print(type(range_samp)) # <class 'range'>
print(range_samp) # range(0, 5)
list_samp = list(range_samp)
print(list_samp) # [0, 1, 2, 3, 4]

・ Reference of list value ・ ・ ・ Omitted because it is exactly the same concept as cpp vector (random access).

・ How to use slices Convenient! !! !! !! I think this is the strength of Python! !!

list_num = [0,1,2,3,4]
print(list_num[1:4]) #The first to "third" are output

list_num = [0,1,2,3,4,5,6,7,8,9,10]
print(list_num[0:11:2]) #Output only even numbers from 0 to 10

-Get the length of the list In cpp, you can get the length by .size (). Use the len () method in Python!

list_two_dim = [[1,1,1,1,1],[2,2,2]]
print(len(list_two_dim)) # 2
print(len(list_two_dim[1])) # 3

-How to use the append () method


list_a = [1,2,3]
list_b = [4,5]
list_a.append(list_b)
print(list_a) # [1, 2, 3, [4, 5]]

-How to use the extend () method

list_c = [1,3,5,7,9,11]
list_d = [2,4,6]
list_c.extend(list_d)
print(list_c) # [1, 3, 5, 7, 9, 11, 2, 4, 6]

・ How to use the del () method

list_num = [1,2,3,4,5,6,7,8,9,10]
del list_num[1:3] #1st~Up to the second is deleted
print(list_num)

I also tackled the challenge:

Sample answer Python
list_hundred = list(range(100)) # range()Is()0 by putting a number inside~Numbers you put in-Make a value of 1
print(list_hundred)

print(list_hundred[0:100:2]) #Output only even numbers using slice
print(list_hundred[1:100:2]) #Use slice to output only odd numbers

sum1 = 0
for i in range(0,100,2):
    sum1 += list_hundred[i]
print(sum1)

sum2 = 0
for i in range(1,100,2):
    sum2 += list_hundred[i]
print(sum2)

sum_all = 0
for i in range(100):
    sum_all += list_hundred.pop()
print(sum_all)

print(list_hundred)

Summary of how to use 10 list [Part 2](Learning time: 2020/06/04 20:02)

This section is also unique to Python, so I worked on it all.

・ In (Does the list include the search target?) Not in (Does the list include the search target?)

list_num = [1,2,3,4]
print(1 in list_num)
print(100 in list_num)
print(100 not in list_num)
 
list_str = ['cat','dog','bug','bag']
print('dog' in list_str)
print('pokemon' in list_str)
print('pokemon' not in list_str)

・ Count () method

list_num = [1,2,3,45,6]
print(list_num.count(1)) # 1
print(list_num.count(5)) # 0

・ Sorting of 2D list

list_product = [['20200219', '4', 'Candy' , 1, 100],
                ['20200120', '3', 'Gum' , 1, 80],
                ['20200301', '5', 'Pocky' , 2, 120],
                ['20200320', '1', 'Gummies' , 1, 100],
                ['20200220', '5', 'Pocky', 3, 120],
                ['20200104', '2', 'Potato chips', 2, 100]]
                
func = lambda p:p[1] #p takes the element no1 of the argument name p

print(func(list_product[1])) #3 Take the product ID of the first element from the front

list_new_num = [func(i) for i in list_product]
print(list_new_num) # ['4', '3', '5', '1', '5', '2']


List comprehension

It's very convenient, so I definitely want to master it here.


list_num = [1,3,4,55,33,100,6]
list_new = [i for i in list_num]
print(list_new) # [1, 3, 4, 55, 33, 100, 6]Is output

list_new2 = [i for i in list_num if i % 2 == 0]
print(list_new2) # [4, 100, 6]Is output

list_new3 = [i**3 for i in list_num if i % 2 == 1]
print(list_new3) # [1, 27, 166375, 35937]
 
list_new4 = [i for i, obj in enumerate(list_num) if obj == 3] #While judging the value of the list with an if statement,Get the matching element number
print(list_new4) # 1

・ Unpack

list_dog_list = [['Pochi', 'Shiba inu', 10],
                 ['Leo', 'Bulldog', 15],]

#Dividing the data in the list into variables is called unpack.
#Output while unpacking
for name, breed, weight in list_dog_list:
    print(name, breed, weight)

I also tackled the challenge:

Sample answer Python
#Part 1
list_product = [['20200219', '4', 'Candy' , 1, 100],
                ['20200120', '3', 'Gum' , 1, 80],
                ['20200301', '5', 'Pocky' , 2, 120],
                ['20200320', '1', 'Gummies' , 1, 100],
                ['20200220', '5', 'Pocky', 3, 120],
                ['20200104', '2', 'Potato chips', 2, 100]]
    
#Part 2
#Sort and display by product name
list_product.sort(key=lambda product:product[2])
print(list_product)

#Part 3
#Sort and display by sales date
list_product.sort(key=lambda product:product[0])
print(list_product)

#Part 4
#Sort by total amount
list_product.sort(key=lambda product:product[3]*product[4])
print(list_product)

#Part 5
pockey_count = [p for _,_,p,_,_ in list_product]
print(pockey_count.count('Pocky'))

#Part 6
pockey_dates = [date for date, _, p, _, _ in list_product if p == 'Pocky']
print(pockey_dates)

#Part 7
pockey_sum = 0

for d, i, n, c, m in list_product:
    if n == 'Pocky':
        pockey_sum += c * m
print(pockey_sum)

11 How to use tuples [From basics to applications](Learning time: 2020/06/04 21:29)

tuple: immutable (elements can be referenced, elements can be searched, but element values cannot be changed)

Summary of how to use 12 sets (aggregates) [From basics to applications](2020/06/05 8:28)

・ About set I'm familiar with the cpp set, so I'll just review it briefly.

# set
x = {'a','b','c','d'}

z = {1,'a',2,'b'}

print(x) # {'c', 'd', 'a', 'b'}
print(x) # {'c', 'd', 'a', 'b'}
print(x) # {'c', 'd', 'a', 'b'}

y = set("shinjukuekimae")
print(y) # {'k', 'e', 'a', 'j', 'n', 'h', 'u', 'm', 's', 'i'}

num_dict = {num*2 for num in range(4,30,2)}
print(num_dict)

#Add an element to set
department_of_medicine = set()
department_of_medicine.add("abc")
print(department_of_medicine) # {'abc'}

#When inserting a string""If you do not enclose it in, an error will occur
# department_of_medicine.add(def) # SyntaxError: invalid syntax

department_of_medicine.add("surgery")
print(department_of_medicine)

x = department_of_medicine.pop() #Get the 0th element
print(x)
print(department_of_medicine)

・ How to operate set

practice = {"abc","def",'xyz',1,2,3}
print(practice) # {1, 2, 3, 'def', 'abc', 'xyz'}

practice.remove('def')
print(practice) # {1, 2, 3, 'abc', 'xyz'}

practice.discard(1)
print(practice) # {2, 3, 'abc', 'xyz'}
practice.discard(5)
print(practice) # {2, 3, 'abc', 'xyz'}

practice.clear()
print(practice) # set()

practice2 = {"dfe","abc",'eeed',3}

# frozenset()Pin the set documentation with
practice2 = frozenset(practice2)
print(practice2)

practice2.discard("dfe") # 'frozenset' object has no attribute 'discard'

・ Set operation for set

g1 = {"abc","def","eee","ujie"}
g2 = {1,2,4,5,3,9}

# |Take the union using
g3 = g1 | g2 
print(g3) # {1, 2, 3, 4, 5, 'eee', 9, 'abc', 'ujie', 'def'}

# union()Take the union using the method
g4 = g1.union(g2)
print(g4) # {'def', 1, 2, 3, 4, 5, 9, 'eee', 'ujie', 'abc'}

g5 = {1,2,3,4,5}
g6 = {1,"a","b","c","d"}

# &Take the intersection by operator
g7 = g5 & g6
print(g7) # {1}

g8 = g5.intersection(g6)
print(g8) # {1}

#Take the difference set
g9 = g5 - g6
print(g9) # {2, 3, 4, 5}

13 How to make a dictionary [From basic to applied](2020/06/05 10:59)

temp_record = {(2020,6,1):20, (2020,6,2):24,(2020,6,3):35}
print(temp_record) # {(2020, 6, 1): 20, (2020, 6, 2): 24, (2020, 6, 3): 35}

#Conversion to dict
sample1 = dict([("a",1),("b",2),("c",3)])
print(sample1) # {'a': 1, 'b': 2, 'c': 3}

# zip()Creating a dictionary using
sample2 = ["a","b","c"]
sample3 = [1,2,3]
sample4 = dict(zip(sample2,sample3))
print(sample4) # {'a': 1, 'b': 2, 'c': 3}

#Creating a dictionary using keys
sample5 = dict(a = 1, b = 2)
print(sample5) # {'a': 1, 'b': 2}

#Use of inclusion notation
sample6 = {i: i*3 for i in range(2,10,1)}
print(sample6) # {2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27}
 sample = {}
sample['a'] = 1
sample['b'] = 2
sample['c'] = 3
print(sample) # {'a': 1, 'b': 2, 'c': 3}
print(sample.get('b')) # 2

print(sample.pop('a')) #The value 1 is output
sample.clear() 
print(sample) # {}Is output

Recommended Posts

Python beginners publish web applications using machine learning [Part 2] Introduction to explosive Python !!
Python beginners publish web applications using machine learning [Part 1] Introduction
An introduction to Python for machine learning
[Python] Easy introduction to machine learning with python (SVM)
[For beginners] Introduction to vectorization in machine learning
Introduction to machine learning
An introduction to machine learning
Super introduction to machine learning
Machine learning to learn with Nogizaka46 and Keyakizaka46 Part 1 Introduction
[Python] Introduction to graph creation using coronavirus data [For beginners]
Introduction to Python Hands On Part 1
Machine learning summary by Python beginners
<For beginners> python library <For machine learning>
Introduction to Machine Learning Library SHOGUN
[Python machine learning] Recommendation of using Spyder for beginners (as of August 2020)
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy
Introduction to Python Basics of Machine Learning (Unsupervised Learning / Principal Component Analysis)
Python learning memo for machine learning by Chainer Chapter 9 Introduction to scikit-learn
Introduction to Machine Learning: How Models Work
Introduction to Discrete Event Simulation Using Python # 1
I installed Python 3.5.1 to study machine learning
An introduction to OpenCV for machine learning
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
Introduction to ClearML-Easy to manage machine learning experiments-
Introduction to Discrete Event Simulation Using Python # 2
Take the free "Introduction to Python for Machine Learning" online until 4/27 application
An introduction to self-made Python web applications for a sluggish third-year web engineer
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
[Super Introduction to Machine Learning] Learn Pytorch tutorials
An introduction to machine learning for bot developers
Machine learning starting with Python Personal memorandum Part2
Procedure to use TeamGant's WEB API (using python)
[Super Introduction] Machine learning using Python-From environment construction to implementation of simple perceptron-
Introducing 4 ways to monitor Python applications using Prometheus
Machine learning starting with Python Personal memorandum Part1
Introduction to Tornado (1): Python web framework started with Tornado
Python & Machine Learning Study Memo ②: Introduction of Library
[Machine learning] Supervised learning using kernel density estimation Part 2
EV3 x Python Machine Learning Part 2 Linear Regression
Try using the Python web framework Tornado Part 1
Machine learning beginners tried to make a horse racing prediction model with python
[Machine learning] Supervised learning using kernel density estimation Part 3
[Introduction to Python3 Day 20] Chapter 9 Unraveling the Web (9.1-9.4)
[Super Introduction to Machine Learning] Learn Pytorch tutorials
[Python3] Let's analyze data using machine learning! (Regression)
How to Introduce IPython (Python2) to Mac OS X-Preparation for Introduction to Machine Learning Theory-
Try using the Python web framework Tornado Part 2
Introduction to Programming (Python) TA Tendency for beginners
[Python] Beginners troubleshoot while studying Django web applications
Python learning notes for machine learning with Chainer Chapters 11 and 12 Introduction to Pandas Matplotlib
What I learned about AI / machine learning using Python (1)
Machine learning python code summary (updated from time to time)
Create machine learning projects at explosive speed using templates
What I learned about AI / machine learning using Python (3)
Preparing to start "Python machine learning programming" (for macOS)
Machine learning beginners try to make a decision tree
Attempt to include machine learning model in python package
[Introduction to Python] How to stop the loop using break?
[Machine learning] Try to detect objects using Selective Search
Memo for building a machine learning environment using Python