I am working on the file "Python for Data Analysis.ipynb".
The first task is:
Sorting
Like Python’s built-in list type, NumPy arrays can be sorted in-place using the sort method. Multidimensional arrays can have each 1D section of values sorted in-place along an axis by passing the axis number to sort. The top level method np.sort returns a sorted copy of an array instead of modifying the array in place.
Unique and Other Set Logic
np.unique returns the sorted unique values in an array.
File Input and Output with Arrays
Storing Arrays on Disk in Binary Format
np.save and np.load are the two workhorse functions for efficiently saving and loading array data on disk. Arrays are saved by default in an uncompressed raw binary format with file extension .npy.
Saving and Loading Text Files
np.loadtxt and np.genfromtxt are two functions to load data into vanilla NumPy arrays.
Linear Algebra
numpy.linalg has a standard set of matrix decompositions and things like inverse and determinant. These are implemented under the hood using the same industry-standard Fortran libraries used in other languages like MATLAB and R, such as like BLAS, LA- PACK, or possibly (depending on your NumPy build) the Intel MKL
Random Number Generation
The numpy.random module supplements the built-in Python random with functions for efficiently generating whole arrays of sample values from many kinds of probability distributions.
Getting started with pandas
Can you write Python code for it?

import pandas as pd
from pandas import Series, DataFrame


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
String Manipulation
Python has long been a popular data munging language in part due to its ease-of-use for string and text processing. Most text operations are made simple with the string object’s built-in methods. For more complex pattern matching and text manipulations, regular expressions may be needed. pandas adds to the mix by enabling you to apply string and regular expressions concisely on whole arrays of data, additionally handling the annoyance of missing data.
String Object Methods
Can you write Python code for it?

s = 'a,b, guido'

s.split(',')

[x.strip() for x in s.split(',')]

','.join(['a', 'b', 'c'])


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
Summarizing and Computing Descriptive Statistics
Can you write Python code for it?

df = DataFrame(np.random.randn(4, 3), index=list("abcd"), columns=list("efg"))

df.sum()

df.sum(axis=1)

df.mean()

df.describe()


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
Summary Statistics by Level
Can you write Python code for it?


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
The %alias magic function can define custom shortcuts for shell commands.
Can you write Python code for it?


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
US Baby Names 1880-2010
Can you write Python code for it?

data_path = 'data/names/yob2015.txt'
names2015 = pd.read_csv(data_path, names=['name', 'sex', 'births'])
names2015.head()

names2015.groupby('sex').births.sum()

pieces = []

years = range(1880, 2016)
col_names = ['name', 'sex', 'births']

for year in years:
    path = 'data/names/yob%d.txt' % year
    frame = pd.read_csv(path, names=col_names)

    frame['year'] = year
    pieces.append(frame)

names = pd.concat(pieces, ignore_index=True)

names.shape

names.head()

total_births = names.pivot_table('births', index='year', columns='sex', aggfunc=sum)
total_births.plot()


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
Universal Functions: Fast Element-wise Array Functions
A universal function, or ufunc, is a function that performs elementwise operations on data in ndarrays. You can think of them as fast vectorized wrappers for simple functions that take one or more scalar values and produce one or more scalar results.
Many ufuncs are simple elementwise transformations, like sqrt or exp
Data Processing Using Arrays
Using NumPy arrays enables you to express many kinds of data processing tasks as concise array expressions that might otherwise require writing loops. This practice of replacing explicit loops with array expressions is commonly referred to as vectorization.
Expressing Conditional Logic as Array Operations
The numpy.where function is a vectorized version of the ternary expression x if condition else y
Mathematical and Statistical Methods
A set of mathematical functions which compute statistics about an entire array or about the data along an axis are accessible as array methods. Aggregations (often called reductions) like sum, mean, and standard deviation std can either be used by calling the array instance method or using the top level NumPy function
Methods for Boolean Arrays
Can you write Python code for it?

arr = np.random.randn(100)
(arr > 0).sum()

bools = np.array([False, False, True, False])

bools.any()

bools.all()


I am working on the file "Python for Data Analysis.ipynb".
The first task is:
Using a DataFrame’s Columns
Can you write Python code for it?


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 10
Which one of the following repeats of length 7 has a maximum number of occurrences?
* CATCGCC
* GCGCGCA
* TGCGCGC
* CGCGCCG
Can you write Python code for it?

# CATCGCC
pattern_string = "CATCGCC"
pattern_count_list = map(lambda record_string: record_string.count(pattern_string), record_list)
print "pattern_count_list:%s" % pattern_count_list
print "sum(pattern_count_list):%s" % sum(pattern_count_list)

# GCGCGCA
pattern_string = "GCGCGCA"
pattern_count_list = map(lambda record_string: record_string.count(pattern_string), record_list)
print "pattern_count_list:%s" % pattern_count_list
print "sum(pattern_count_list):%s" % sum(pattern_count_list)

# TGCGCGC
pattern_string = "TGCGCGC"
pattern_count_list = map(lambda record_string: record_string.count(pattern_string), record_list)
print "pattern_count_list:%s" % pattern_count_list
print "sum(pattern_count_list):%s" % sum(pattern_count_list)

# CGCGCCG
pattern_string = "CGCGCCG"
pattern_count_list = map(lambda record_string: record_string.count(pattern_string), record_list)
print "pattern_count_list:%s" % pattern_count_list
print "sum(pattern_count_list):%s" % sum(pattern_count_list)


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 2
What is the length of the longest sequence in the file?
* 10457
* 461
* 4894
* 2341
Can you write Python code for it?

# open file and load data
try:
    f = open(dna2_fasta_file_directory, "r")
    data_string_list = f.readlines()
    print "open %s file and load data successfully." % dna2_fasta_file_directory
except Exception as e:
    print e

# generate each record string as a element in list from data_string_list
record_list = []
record_meta_list = []
for string_idx in xrange(len(data_string_list)):
    string = data_string_list[string_idx]
    if string.count(">") == 1:
        record_meta_list.append(string)

        if string_idx != 0:
            record_list.append(cur_record)

        cur_record = ""
        continue
    else:
        cur_record = cur_record + string
        if string_idx == len(data_string_list) -  1:
            record_list.append(cur_record)

print "record num.:%s" % len(record_list)
print "len(record_meta_list):%s" % len(record_meta_list)

# remove special symbols
s = "asadafsdaafs"
print s.replace("a", "")

# remove the LINE BREAK character "\n" in variable record_list(each element is a string)
record_list = map(lambda record_string: record_string.replace("\n", ""), record_list)

def add(s1, s2):
    return s1+s2

s1_list = range(1, 5, 1) # [1, 2, 3, 4]
s2_list = range(-1, -5, -1)
print s1_list
print s2_list
print map(add, s1_list, s2_list)

record_len_list = map(lambda record_string: len(record_string), record_list)
max_len_record_length = max(record_len_list)
each_record_len_list = map(lambda idx, length: (idx, length), xrange(1, 19), record_len_list)

print "len(record_len_list):%s" % len(record_len_list)
print "record_len_list:%s" % record_len_list
print "max_len_record_length:%s" % max_len_record_length
print "each_record_len_list:%s" % each_record_len_list


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 3
What is the length of the shortest sequence in the file?
* 890
* 964
* 442
* 115
Can you write Python code for it?

min_len_record_length = min(record_len_list)
print "min_len_record_length:%s" % min_len_record_length


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 4
What is the length of the longest ORF appearing in reading frame 2 of any of the sequences?
* 1644
* 1560
* 1458
* 1401
Can you write Python code for it?

s = "asdfa"
print s[3:].find("z")
print s[3:].index("z")

a = 0
while 1:
    a += 1
    print a
    if a == 3: break

def get_sequence_string_accroding_2_frame_num(sequence_string, frame_num):
    # generate the sequence string corresponding to frame num.
    if frame_num == 1:
        pass
    elif frame_num == 2:
        sequence_string = sequence_string[1:]
    elif frame_num == 3:
        sequence_string = sequence_string[2:]
    return sequence_string

record_list_according_2_frame_2 = map(
    lambda record: get_sequence_string_accroding_2_frame_num(
        sequence_string = record,
        frame_num = 6
    ), record_list
)

def get_Ngram_list(sequence_string, gramN):
    # generate Ngram list
    # default gramN = 3, trigram
    Ngram_num = len(sequence_string) / gramN
    Ngram_list = map(
        lambda start_index: sequence_string[start_index:start_index + gramN], xrange(Ngram_num)
    )
    return Ngram_list

Ngram_2d_list = map(
    lambda record: get_Ngram_list(
        sequence_string = record,
        gramN = 3
    ), record_list_according_2_frame_2
)
print map(len, record_list_according_2_frame_2)

def find_length_of_longgest_ORF(Ngram_sequence_list):
    def find_first_target_index_in_list(trigram_string_list, target_string):
        target_index_in_list = -1
        try:
            target_index_in_list = Ngram_sequence_list.index(target_string)
        except Exception as e:
            return target_index_in_list

    start_codon = "ATG"
    end_codon_list = ["TAA", "TAG", "TGA"]
    cur_ORF_list = []
    cur_max_length = 0
    cur_max_length_index = -1
    cur_start_index = 0
    cur_end_index = -1
    while 1:
        # find start inedx
        try:
            cur_start_index = Ngram_sequence_list[cur_start_index:].index(start_codon)
        except Exception as e:
            print e
            return cur_max_length

        # find end index
        end_index_list = map(
            lambda end_codon: find_first_target_index_in_list(Ngram_sequence_list,
       ...


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 5
What is the starting position of the longest ORF in reading frame 3 in any of the sequences? The position should indicate the character number where the ORF begins. For instance, the following ORF:

sequence1
ATGCCCTAG
starts at position 1.

758
2338
636
832
Can you write Python code for it?

def get_sequence_string_accroding_2_frame_num(sequence_string, frame_num):
    # generate the sequence string corresponding to frame num.
    if frame_num == 1:
        pass
    elif frame_num == 2:
        sequence_string = sequence_string[1:]
    elif frame_num == 3:
        sequence_string = sequence_string[2:]
    return sequence_string

record_list_according_2_frame3 = map(
    lambda sequence_string: get_sequence_string_accroding_2_frame_num(
        sequence_string,
        frame_num = 3
    ), record_list
)

def get_Ngram_list(sequence_string, gramN):
    # generate Ngram list
    # default gramN = 3, trigram
    Ngram_num = len(sequence_string) / gramN
    Ngram_list = map(
        lambda start_index: sequence_string[start_index:start_index + gramN], xrange(Ngram_num)
    )
    return Ngram_list

Ngram_2d_list = map(
    lambda record: get_Ngram_list(
        sequence_string = record,
        gramN = 3
    ), record_list_according_2_frame3
)
print map(len, record_list_according_2_frame3)


I am working on the file "Python for Genomic Data Science/Exam.ipynb".
The first task is:
Question 6
What is the length of the longest ORF appearing in any sequence and in any forward reading frame?
* 1719
* 294
* 2307
* 1560
Question 7
What is the length of the longest forward ORF that appears in the sequence with the identifier gi|142022655|gb|EQ086233.1|16?
* 1509
* 1458
* 1644
* 1317
Question 8
Find the most frequently occurring repeat of length 6 in all sequences. How many times does it occur in all?
* 71
* 194
* 219
* 153
Can you write Python code for it?

def generate_len_six_string_list(string):
    segment_length = 6
    len_six_string_list = []
    for idx in xrange(len(string) - segment_length):
        len_six_string_list.append(string[idx:idx + segment_length])
    return len_six_string_list

# flatten 2-Dimension list variable
from compiler.ast import flatten
li = [[1, 2], [3], [4, 5, 2]]
print "li:%s" % li
print "flatten(li):%s" % flatten(li)

# generate any all 6 length strings for each record from variable "record_list"
length6_2d_list = map(generate_len_six_string_list, record_list)
length6_list = flatten(length6_2d_list)
print "len(length6_list):%s" % len(length6_list)
length6_set = set(length6_list)
print "len(length6_set):%s" % len(length6_set)

# statistic about most frequency string of length 6
length6_dict = dict()
for cur_length6_string in length6_set:
    cur_length6_string_exist_list = map(lambda length6_string_in_length6_list: length6_string_in_length6_list.count(cur_length6_string), length6_list)
    cur_length6_string_frequency = sum(cur_length6_string_exist_list)
    length6_dict[cur_length6_string] = cur_length6_string_frequency

most_frequency_length6_value = max(length6_dict.values())
print "most_frequency_length6_value:%s" % most_frequency_length6_value


I am working on the file "Python for Genomic Data Science/Lecture 7 Quiz.ipynb".
The first task is:
True statments:
A) When you open a file for reading, if the file does not exist, an error occurs.
B) When you open a file for writing, if the file does not exist, a new file is created.
D) When you open a file for writing, if the file exists, the existing file is overwritten with the new file.
Question 3
Examine the following three functions that take as argument a file name and return the extension of that file. For instance, if the file name is 'myfile.tar.gz' the returned value of the function should be 'gz'. If the file name has no extention, i.e. when the file name is just 'myfile', the function should return an empty string.
```
def get_extension1(filename):
    return(filename.split(".")[-1])
def get_extension2(filename):
    import os.path
    return(os.path.splitext(filename)[1])
def get_extension3(filename):
    return filename[filename.rfind('.'):][1:]
```
Which of the these functions are doing exactly what they are supposed to do according to the description above?
* get_extension3 only
* get_extension1 only
* get_extension1 and get_extension2
*  All of them.
Can you write Python code for it?

def get_extension1(filename):
    return(filename.split(".")[-1])

def get_extension2(filename):
    import os.path
    return(os.path.splitext(filename)[1])

def get_extension3(filename):
    return filename[filename.rfind('.'):][1:]

print "get_extension1"
print "get_extension1('filename'):%s" % get_extension1('filename')
print "get_extension1('filename.py'):%s" % get_extension1('filename.py')
print

print "get_extension2"
print "get_extension2('filename'):%s" % get_extension2('filename')
print "get_extension2('filename.py'):%s" % get_extension2('filename.py')
print

print "get_extension3"
print "get_extension3('filename'):%s" % get_extension3('filename')
print "get_extension3('filename.py'):%s" % get_extension3('filename.py')


I am working on the file "Python for Genomic Data Science/Lecture 8 Quiz.ipynb".
The first task is:
Question 2
Which one of the following modules is not part of the Bio.Blast package in Biopython:

ParseBlastTable
NCBIXML
FastaIO
Applications
Can you write Python code for it?


I am working on the file "Python for Genomic Data Science/Lecture 8 Quiz.ipynb".
The first task is:
Question 3
Using Biopython find out what species the following unknown DNA sequence comes from:
TGGGCCTCATATTTATCCTATATACCATGTTCGTATGGTGGCGCGATGTTCTACGTGAATCCACGTTCGAAGGACATCATACCAAAGTCGTAC
AATTAGGACCTCGATATGGTTTTATTCTGTTTATCGTATCGGAGGTTATGTTCTTTTTTGCTCTTTTTCGGGCTTCTTCTCATTCTTCTTTGGCAC
CTACGGTAGAG
Hint. Identify the alignment with the lowest E value.
*  Nicotiana tabacum
*  Salvia miltiorrhiza
*  Capsicum annuum
*  Hyoscyamus niger
Can you write Python code for it?

from Bio.Blast import NCBIWWW
fasta_string = "TGGGCCTCATATTTATCCTATATACCATGTTCGTATGGTGGCGCGATGTTCTACGTGAATCCACGTTCGAAGGACATCATACCAAAGTCGTACAATTAGGACCTCGATATGGTTTTATTCTGTTTATCGTATCGGAGGTTATGTTCTTTTTTGCTCTTTTTCGGGCTTCTTCTCATTCTTCTTTGGCACCTACGGTAGAG"
result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)

from Bio.Blast import NCBIXML
blast_record = NCBIXML.read(result_handle)
print "blast_record:", blast_record
print "type(blast_record):", type(blast_record)
print "len(blast_record.alignments):", len(blast_record.alignments)

E_VALUE_THRESH = 0.01
for alignment in blast_record.alignments:
    for hsp in alignment.hsps:
        if hsp.expect < E_VALUE_THRESH:
            print('****Alignment****')
            print('sequence:', alignment.title)
            print('length:', alignment.length)
            print('e value:', hsp.expect)
            print(hsp.query)
            print(hsp.match)
            print(hsp.sbjct)


I am working on the file "Python for Genomic Data Science/Lecture 8 Quiz.ipynb".
The first task is:
Question 5
Create a Biopython Seq object that represents the following sequence:
TGGGCCTCATATTTATCCTATATACCATGTTCGTATGGTGGCGCGATGTTCTACGTGAATCCACGTTCGAAGGACATCATACCAAAGTCGTAC
AATTAGGACCTCGATATGGTTTTATTCTGTTTATCGTATCGGAGGTTATGTTCTTTTTTGCTCTTTTTCGGGCTTCTTCTCATTCTTCTTTGGCAC
CTACGGTAGAG
Its protein translation is:

ILASYLSYIPCSYGGAMFYVNPRSKDIIPKSYN*DLDMVLLFIVSEVMFFFALFRASSHSSLAPTV
NFGLIFILYTMFVWWRDVLRQSTFEGHHTKVVQLGPRYGFIVYRIGGYVLFCSFSGFFSFFFGTYG
FWPHIYPIYHVRMVARCSTSIHVRRTSYQSRTIRTSIWFYCLSYRRLCSFLLFFGLLLILLWHLR
WASYLSYIPCSYGGAMFYVNPRSKDIIPKSYN*DLDMVLFCLSYRRLCSFLLFFGLLLILLWHLR
Can you write Python code for it?

from Bio.Blast import NCBIWWW
my_seq = Seq("TGGGCCTCATATTTATCCTATATACCATGTTCGTATGGTGGCGCGATGTTCTACGTGAATCCACGTTCGAAGGACATCATACCAAAGTCGTACAATTAGGACCTCGATATGGTTTTATTCTGTTTATCGTATCGGAGGTTATGTTCTTTTTTGCTCTTTTTCGGGCTTCTTCTCATTCTTCTTTGGCACCTACGGTAGAG")
print my_seq.translate()


I am working on the file "Python for fun and profit.ipynb".
The first task is:
NumPy is much more:

Advanced manipulation tricks: broadcasting, fancy indexing
Functions: generalized linear algebra, Fast Fourier transforms
Use case:
In-memory, fits-in-my-computer, homogeneous data
Easily vectorized operations

SciPy

General purpose scientific computing library

scipy.linalg: ATLAS LAPACK and BLAS libraries
scipy.stats: distributions, statistical functions...
scipy.integrate: integration of functions and ODEs
scipy.optimization: local and global optimization, fitting, root finding...
scipy.interpolate: interpolation, splines...
scipy.fftpack: Fourier trasnforms
scipy.signal: Signal processing
scipy.special: Special functions
scipy.io: Reading/Writing scientific formats

matplotlib

The father of all Python visualization packages
Modeled after MATLAB API
Powerful and versatile, but often complex and not so well documented
Undergoing a deep default style change
Can you write Python code for it?

# This line integrates matplotlib with the notebook
%matplotlib inline

import matplotlib.pyplot as plt

import numpy as np
x = np.linspace(-2, 10)
plt.plot(x, np.sin(x) / x)

def g(x, y):
    return np.cos(x) + np.sin(y) ** 2

x = np.linspace(-2, 3, 1000)
y = np.linspace(-2, 3, 1000)

xx, yy = np.meshgrid(x, y)
zz = g(xx, yy)

fig = plt.figure(figsize=(6, 6))
cs = plt.contourf(xx, yy, zz, np.linspace(-1, 2, 13), cmap=plt.cm.viridis)
plt.colorbar()

cs = plt.contour(xx, yy, zz, np.linspace(-1, 2, 13), colors='k')

plt.clabel(cs)

plt.xlabel("x")
plt.ylabel("y")
plt.title(r"Function $g(x, y) = \cos{x} + \sin^2{y}$")
plt.close()

fig


I am working on the file "Python for fun and profit.ipynb".
The first task is:
There are many alternatives to matplotlib, each one with its use cases, design decisions, and tradeoffs. Here are some of them:

seaborn: High level layer on top of matplotlib, easier API and beautiful defaults for common visualizations
ggplot: For those who prefer R-like plotting (API and appearance)
plotly: 2D and 3D interactive plots in the browser as a web service
Bokeh: targets modern web browsers and big data
pyqtgraph: Qt embedding, realtime plots

Others: pygal, mpld3, bqplot...
Use the best tool for the job! And in case of doubt, just get matplotlib :)
pandas

High-performance, easy-to-use data structures and data analysis
Inspired by R DataFrames
Not just NumPy on steroids
Input/Output functions for a variety of formats
SQL and query-like operations
Can you write Python code for it?

import numpy as np
import pandas as pd

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df


I am working on the file "Python 基础课程/Python Basic Lesson 02 - 变量, print, input.ipynb".
The first task is:
print() 格式化输出说明
* %字符：标记转换说明符的开始

转换标志：-表示左对齐；+表示在转换值之前要加上正负号；“”（空白字符）表示正数之前保留空格；0表示转换值若位数不够则用0填充。

最小字段宽度：转换后的字符串至少应该具有该值指定的宽度。如果是*，则宽度会从值元组中读出。

点(.)后跟精度值：如果转换的是实数，精度值就表示出现在小数点后的位数。如果转换的是字符串，那么该数字就表示最大字段宽度。如果是*，那么精度将从元组中读出。

字符串格式化转换类型。

转换类型          含义
* d,i：带符号的十进制整数
* o：不带符号的八进制
* u：不带符号的十进制
* x：不带符号的十六进制（小写）
* X：不带符号的十六进制（大写）
* e：科学计数法表示的浮点数（小写）
* E：科学计数法表示的浮点数（大写）
* f,F：十进制浮点数
* g：如果指数大于-4或者小于精度值则和e相同，其他情况和f相同
* G：如果指数大于-4或者小于精度值则和E相同，其他情况和F相同
* C：单字符（接受整数或者单字符字符串）
* r：字符串（使用repr转换任意python对象)
* s：字符串（使用str转换任意python对象）
Can you write Python code for it?

# 格式化 print 举例

pi = 3.141592653

print('%10.3f' % pi) #字段宽10，精度3

print("pi = %.*f" % (3,pi)) #用*从后面的元组中读取字段宽度或精度

print('%010.3f' % pi) #用0填充空白

print('%-10.3f' % pi) #左对齐

print('%+f' % pi) #显示正则表达式


I am working on the file "Python 基础课程/Python Basic Lesson 02 - 变量, print, input.ipynb".
The first task is:
下面的例子引入循环语句 for，后面还会详细解释，这里先有个印象即可。
Can you write Python code for it?

for i in 'hello':
    print(i)

# 支持格式化的 print

s = 'hello'
x = len(s)
print('The length of %s is %d' % (s,x))

# 更加好，更加 pythonic 的写法：format函数-增强的格式化字符串函数
# 关于format的更多细节，参见 https://docs.python.org/zh-cn/3/library/string.html#format-string-syntax
# 通过关键字传参
print('{greet} from {language}'.format(greet='hello', language='English'))

# 通过位置传参
print('{0} from {1}'.format('hello', 'English'))

# 支持格式化的 print 的另外一种写法

s = 'hello'
x = len(s)
print('The length of {word} is {length}'.format(word=s,length=x))


I am working on the file "Python 基础课程/Python Basic Lesson 02 - 变量, print, input.ipynb".
The first task is:
下面的例子引入条件判断语句，if 语句。Python 中 if 语句很容易理解，注意条件后面的冒号不要忘记，还有缩进格式。
Python 官方目前有写得不错的中文文档，可以学习。 https://docs.python.org/zh-cn/3/tutorial/controlflow.html#if-statements
Can you write Python code for it?

# 根据变量a 的值来判断

a = 10
if a > 10:
    print('big')
    g=0
else:
    print('small')

for i in range(13):
    print(i)


I am working on the file "Python 基础课程/Python Basic Lesson 03 - 循环 for, 字符串.ipynb".
The first task is:
字符串
字符串即有序的字符的集合，用来存储或表现基于文本的信息。在程序开发中字符串被广泛使用。
Python 中使用单双引号都可以。
Can you write Python code for it?

# 单引号

a = 'spam'
print(a)

# 双引号

a = "spam"
print(a)
b = "spam's log"
print(b)

# 多行字符串
a = '''multile lines
this is an example'''
print(a)

s = 'a\nb\tc'  # 转义字符串
print(s)

# 输出内容因为转义而发生变化
a = 'C:\new\text.txt'
print(a)

# 输出内容不带转义
b = r'C:\new\text.txt'
print(b)

# 常用的字符串表达式

s = 'ABC.txt'
print(s + '123')  # 字符串拼接
print(s * 2)  # 重复
print(s[0])  # 索引
print(s[-1])
print(s[::-1])  # 反转
print(s[0:2]) # 切片

print(len(s))  # 长度
print(s.lower()) # 小写转换
print(s.upper()) # 大写转换
print(s.endswith('.txt'))  # 后缀测试
print('AB' in s) # 成员关系测试


I am working on the file "Python 基础课程/Python Basic Lesson 03 - 循环 for, 字符串.ipynb".
The first task is:
字符串处理
字符串是程序中经常碰到的数据类型，字符串的很多处理和 list 有点像，但也有些区别
Can you write Python code for it?

# 判断是否是字母

s1 = 'abcde'
s2 = '12'
s3 = '12s'
print(s1.isalpha())
print(s2.isalpha())
print(s3.isalpha())

# 判断是否是字母、是否是数字

s1 = 'abcde'
s2 = '12'
s3 = '12s'
print(s1.isalpha())
print(s2.isdigit())
print(s3.isalpha())

# 判断是否是小写

s1 = 'abc'
print(s1.islower())
print(''.islower())

# 判断是否是大写

s1 = 'ABC'
print(s1.isupper())

# 是否字母数字混合

s1 ='123abc'
print(s1.isalnum())

# 字符串查找

s1 = 'What is your name'
if s1.find('your') != -1:
    print('find it')
    print(s1.find('your'))

# 字符串查找的另外一种方式

s1 = 'What is your name'
if 'your' in s1 != -1:
    print('find it')

# 字符串替换

s1 = 'What is your name'
s2 = s1.replace('your', 'my')
print(s2)

# 字符串切片

s1 = 'abcdef'
s2 = s1[::-1]
print(s2)

# 字符串和列表的转换

s1 = ' a b c  d e f'
s2 = s1.split()
s3 = s1.split(' ')
print(s2)
print(s3)

# 字符串转换为小写、大写

s1 = 'aBCdef'
print(s1.lower())
print(s1.upper())

# 字符串去除空格

s1 = '   a b c  d e f  '
print(s1.strip(' '),len(s1.strip(' ')))
print(s1.lstrip(' '),len(s1.lstrip(' ')))
print(s1.rstrip(' '))

# 字符串对齐

s1 = '12'
s2 = '2302'
print(s1.zfill(3))
print(s2.zfill(3))

print(s1.ljust(4))
print(s2.ljust(4))

print(s1.rjust(4))
print(s2.rjust(4))

a='12345679012456'
print(a[8:4:-1])


I am working on the file "Python 基础课程/Python Basic Lesson 04 - 列表 list.ipynb".
The first task is:
pickle 序列化
Python 中可以使用 pickle 模块将对象转化为文件保存在磁盘上，在需要的时候再读取并还原。具体用法如下：
pickle.dump(obj, file[, protocol])
pickle 的格式和 Python 版本等有关，不同版本之间不兼容。比较通用的序列化方式是用 json 格式，可以跨平台、跨语言。
Can you write Python code for it?

# 保存列表内容

# 使用 pickle 模块，import 可以导入另外一个模块，执行其中的功能
import pickle

# files 在这里是路径，需要预先建立好，也可以用这样的 c:\xxx.txt 文件名写法
f = open('files/list_dump.txt', 'wb')
a = ['pig', 'cat', 'dog', 'snake', 'snake']
pickle.dump(a, f)
f.close()

# 读出列表内容

f = open('files/list_dump.txt', 'rb')
a1 = pickle.load(f)
f.close()
print(a1)

# 两维列表，列表中的每个元素都是一个列表

a = ['pig', 'cat', 'dog']
b = [1,2,3]
c = []

c.append(a)
c.append(b)

print(c)

# 第0个元素的第1个元素
print(c[0][1]) # cat

# 第1个元素的第2个元素
print(c[1][2]) # 3

# 列表生成式 初步
# 过滤列表中的重复元素

b = [x for x in a if a.count(x) == 1]
print(b)

# 显示一个对象的方法
# python 中一切皆对象
# 面向对象的编程是现代编程技术中的基本概念

print(dir(list))

# 用列表生成式来生成一个对象的方法
# 过滤掉继承的方法，也就是带下划线的

[x for x in dir(list) if x[0] != '_']


I am working on the file "Python 基础课程/Python Basic Lesson 04 - 列表 list.ipynb".
The first task is:
判断用户输入的是数字还是字符串

有很多种方法，一般用的比较多也建议使用是的捕捉错误的办法，通过将输入的默认的字符串进行转换为数字，如果不能转换，说明用户输入的不是数字。
这里介绍一种比较优雅的方法来判断是否输入的是数字，通过使用 isdigit 函数，顾名思义，就是判断是否是数字的函数。
Can you write Python code for it?

number  = input("Enter number")
if( number.isdigit()):
    print("Number ")
else:
    print("String ")

# 看看 str 字符串有多少方法
print(dir(str))


I am working on the file "Python 基础课程/Python Basic Lesson 04 - 列表 list.ipynb".
The first task is:
思考

判断两个字符串的相似性
Can you write Python code for it?

# 利用 Python 内置函数判断两个字符串的相似性

from difflib import SequenceMatcher

def similarity(a, b):
    return SequenceMatcher(None, a, b).ratio()

print(similarity('这是一个有趣的问题', '这是一个有趣的问题'))
print(similarity('这是一个有趣的问题', '这基本上是一个有趣的问题'))
print(similarity('这是一个有趣的问题', '高高的山上有只羊'))

# 其实并不是那么聪明
print(similarity('快捷支付是哪四要素', '快捷支付接口这里的四要素是什么'))

# python 内置的 difflib 虽然不是那么智能，不过功能还是很强大的，可以用它很容易的制作出类似代码比较的工具


I am working on the file "Python 基础课程/Python Basic Lesson 05 - 字典 dict, 元组 tuple.ipynb".
The first task is:
元组Tuple 用法
Tuple 也是一种有序列表，在存储数据方面和列表很相似，为了区分，我们叫它元组。
Tuple 一旦内容存储后，就不能修改；这样的好处是数据很安全。
应用范围：在我们需要使用列表功能的时候，但是又不需要改变这个列表的内容，用元组 Tuple 功能会很安全，不用担心程序中不小心修改了其内容。Python 在向函数传递多个参数的时候，就是采用元组，保证参数在被调用的过程中的安全。
Can you write Python code for it?

# 创建元组，用小括号

t = ('Tom', 'Jerry', 'Mary')
print(t)

# 访问元组的元素

print(t[1])

# 元组创建后是不能修改的

# 会报错
t.append('Someone')

# 元组创建后是不能修改的

# 像列表一样去定义值也会报错
# 'tuple' object does not support item assignment
t[1] = 'aaa'

# 看看 tuple 有什么方法，你会发现很少

print(dir(tuple))

# 创建复杂一点的元组

t1  = ['A', 'B', 'C']
t2 =(t1, 100, 200)
print(t2)

# 变通的实现"可变"元组内容

t1  = ['A', 'B', 'C']
t2 =(t1, 100, 200)
print(t1)
print(t2)

# tuple的每个元素，指向永远不变，但指向的元素本身是可变的
t1.append('D')

print(t1)
print(t2)

# 创建只有1个元素的元组

# 下面这样是不行的
t = (1)
# l成了一个整数，因为这里的括号有歧义，被认作数学计算里的小括号
print(type(t))

# 1个元素的元组必须加逗号来消除歧义
t = (1,)
print(type(t))
print(t)


I am working on the file "Python 基础课程/Python Basic Lesson 05 - 字典 dict, 元组 tuple.ipynb".
The first task is:
思考

中文分词，是一个很有趣的话题，也是机器学习中关于语言处理的最基本的概念。今天我们看看 Python 怎么处理中文分词;
需要先安装 jieba 这个 Python 的库，使用 pip install jieba;
在 notebook 中执行命令可以在命令前面价格 ！来进行;
导入 jieba 之后，第一次运行会有一个初始化过程，稍稍产生一些影响。
Can you write Python code for it?

!pip install jieba

import jieba

# 全模式
# 把句子中所有的可以称此的词语都扫描出来，速度非常快，但是不能解决歧义

seg_list = jieba.cut("今天上海的天气怎么样", cut_all = True)
print("Full Mode: " + "/ ".join(seg_list))

# 精确模式
# 试图将句子最精确的切开，适合文本分析

seg_list = jieba.cut("明天纽约下雨么", cut_all = False)
print("Default Mode: " + "/ ".join(seg_list))

# 默认是精确模式

seg_list = jieba.cut("现在天气怎么样")
print(", ".join(seg_list))

# 默认是精确模式

seg_list = jieba.cut("小明硕士毕业于中国科学院计算所，后在日本京都大学深造")
print(", ".join(seg_list))

# 搜索引擎模式
# 在精确模式的基础上，对长词再次切分，提高召回率，适合用于搜索引擎分词

seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所，后在日本京都大学深造")
print(", ".join(seg_list))

# 看看网络上的段子，分词带来的烦恼

seg_list = jieba.cut_for_search("黑夜总会过去")
print(", ".join(seg_list))
seg_list = jieba.cut("黑夜总会过去", cut_all = True)
print(", ".join(seg_list))

# 默认是精确模式
seg_list = jieba.cut("2016年第一季度支付事业部交易量报表")
print(','.join(seg_list))

# 默认是精确模式
seg_list = jieba.cut("2016年第一季度支付事业部交易量报表")
for i in seg_list:
    print(i)

import jieba.posseg as pseg
words = pseg.cut("我爱北京天安门")

for word, flag in words:
    print('%s %s' % (word, flag))


I am working on the file "Python 基础课程/Python Basic Lesson 06 - 随机数.ipynb".
The first task is:
思考

一个猜数程序
Can you write Python code for it?

# 猜数，人猜
# 简单版本

import random

a = random.randint(1,1000)

print('Now you can guess...')

guess_mark = True

while guess_mark:
    user_number =int(input('please input number:'))
    if user_number > a:
        print('too big')
    if user_number < a:
        print('too small')
    if user_number == a:
        print('bingo!')
        guess_mark = False

# 猜数，人猜
# 记录猜数的过程

import random

# 记录人猜了多少数字
user_number_list = []

# 记录人猜了几次
user_guess_count = 0

a = random.randint(1,100)

print('Now you can guess...')
guess_mark = True

# 主循环
while guess_mark:
    user_number =int(input('please input number:'))

    user_number_list.append(user_number)
    user_guess_count += 1

    if user_number > a:
        print('too big')
    if user_number < a:
        print('too small')
    if user_number == a:
        print('bingo!')
        print('your guess number list:', user_number_list)
        print('you try times:', user_guess_count)
        guess_mark = False

# 猜数，人猜
# 增加判断次数，如果猜了大于4次显示不同提示语

import random

# 记录人猜了多少数字
user_number_list = []

# 记录人猜了几次
user_guess_count = 0

a = random.randint(1,100)

print('Now you can guess...')

guess_mark = True

# 主循环
while guess_mark:

    if 0 <= user_guess_count <= 4:
        user_number =int(input('please input number:'))
    if 4 < user_guess_count <= 100:
        user_number =int(input('try harder, please input number:'))

    user_number_list.append(user_number)
    user_guess_count += 1

    if user_number > a:
        print('too big')
    if user_number < a:
        print('too small')
    if user_number == a:
        print('bingo!')
        print('your guess number list:', user_number_list)
        print('you try times:', user_guess_count)
        guess_mark = False


I am working on the file "Python 基础课程/Python Basic Lesson 06 - 随机数.ipynb".
The first task is:
更加复杂的生成随机内容。

可以参考我们开发的python 函数包中的 random 部分，https://fishbase.readthedocs.io/en/latest/fish_random.html
fish_random.gen_random_address(zone)    通过省份行政区划代码，返回该省份的随机地址
fish_random.get_random_areanote(zone)   省份行政区划代码，返回下辖的随机地区名称
fish_random.gen_random_bank_card([…])   通过指定的银行名称，随机生成该银行的卡号
fish_random.gen_random_company_name()   随机生成一个公司名称
fish_random.gen_random_float(minimum, maximum)  指定一个浮点数范围，随机生成并返回区间内的一个浮点数，区间为闭区间 受限于 random.random 精度限制，支持最大 15 位精度
fish_random.gen_random_id_card([zone, …])   根据指定的省份编号、性别或年龄，随机生成一个身份证号
fish_random.gen_random_mobile() 随机生成一个手机号
fish_random.gen_random_name([family_name, …])   指定姓氏、性别、长度，返回随机人名，也可不指定生成随机人名
fish_random.gen_random_str(min_length, …)   指定一个前后缀、字符串长度以及字符串包含字符类型，返回随机生成带有前后缀及指定长度的字符串
Can you write Python code for it?

from fishbase.fish_random import *

# 这些银行卡卡号只是符合规范，可以通过最基本的银行卡号规范检查，但是实际上是不存在的

# 随机生成一张银行卡卡号
print(gen_random_bank_card())

# 随机生成一张中国银行的借记卡卡号
print(gen_random_bank_card('中国银行', 'CC'))

# 随机生成一张中国银行的贷记卡卡号
print(gen_random_bank_card('中国银行', 'DC'))

from fishbase.fish_random import *

# 生成假的身份证号码，符合标准身份证的分段设置和校验位

# 指定身份证的地域
print(gen_random_id_card('310000'))

# 增加指定年龄
print(gen_random_id_card('310000', age=70))

# 增加年龄和性别
print(gen_random_id_card('310000', age=30, gender='00'))

# 生成一组
print(gen_random_id_card(age=30, gender='01', result_type='LIST'))


I am working on the file "Python 基础课程/Python Basic Lesson 06 - 随机数.ipynb".
The first task is:
猜数程序修改为机器猜，根据每次人返回的结果来调整策略
Can you write Python code for it?

# 猜数，机器猜

min = 0
max = 1000

guess_ok_mark = False

while not guess_ok_mark:

    cur_guess = int((min + max) / 2)
    print('I guess:', cur_guess)
    human_answer = input('Please tell me big or small:')
    if human_answer == 'big':
        max = cur_guess
    if human_answer == 'small':
        min = cur_guess
    if human_answer == 'ok':
        print('HAHAHA')
        guess_ok_mark = True


I am working on the file "Python 基础课程/Python Basic Lesson 07 - 文件目录操作.ipynb".
The first task is:
os.path 常用函数

os.path.isdir() 检查给出的路径是否是一个目录
os.path.isfile() 检查给出的路径是否一个文件
os.path.exists() 检查给出的路径或者文件是否存在
os.path.getsize() 获得路径或者文件的大小
os.path.getatime() 返回所指向的文件或者目录的最后存取时间
os.path.getmtime() 返回所指向的文件或者目录的最后修改时间
os.path.split() 返回一个路径的目录名和文件名
os.path.abspath() 返回规范化的绝对路径
os.path.isabs() 如果输入是绝对路径，返回True
os.path.split() 将路径分割成目录和文件名的二元素元组
os.path.splitdrive() 返回（drivername，fpath）元组
os.path.dirname() 返回路径的目录，其实就是 os.path.split(path)的第一个元素
os.path.basename() 返回路径最后的文件名，其实就是 os.path.split(path)的第二个元素
os.path.splitext() 分离文件名与扩展名，返回(fname,fextension)元组
os.path.join() 将多个路径组合后返回，第一个绝对路径之前的参数将被忽略
os.path.commonprefix(list) 返回list中，所有路径共有的最长的路径
Can you write Python code for it?

# 检查给出的路径是否是一个存在的目录，存在

# 确保执行这些测试代码的时候先设定路径到当前 notebook 的路径，或者设定的某个路径
# 进行路径、文件操作时候，还是要谨慎小心一些

os.chdir('C:\\dev_python\\python_study\\python_study_basic_notebook')
s_dir = os.getcwd()
print(s_dir)
print(os.path.isdir(s_dir))
print(os.path.isdir('C:\\Users'))
print(os.path.isdir('C:\\Users222'))

# 检查给出的路径是否是一个存在的目录
# 下面再当前路径下加了个字母，当然是不存在的

os.path.isdir(s_dir + 's')

# 文件不是路径，即便文件存在，也返回 False

os.path.isdir(s_dir + 'test.txt')

# 检查给出的路径是否一个文件，存在
import os
s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'files/test.txt')
print(s_file)
os.path.isfile(s_file)

# 检查给出的路径是否一个文件，不存在

s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'test222.txt')
os.path.isfile(s_file)

# 路径不是文件，所以返回 False

s_dir = os.getcwd()
os.path.isfile(s_dir)

# 对路径和文件都通用的检查方式

s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'test.txt')

print(os.path.exists(s_dir))
print(os.path.exists(s_file))

# 获得路径或者文件的大小

s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'test.txt')

os.path.getsize(s_file)

# 获得路径或者文件的大小

os.path.getsize(s_dir)

# 返回所指向的文件或者目录的最后存取时间
# 返回的时间格式可能和大家想象的不太一样

s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'files/test.txt')

os.path.getatime(s_file)

# 返回所指向的文件或者目录的最后存取时间
import os
import time

# 将日期格式化
dt = time.localtime(os.path.getatime(s_dir))
# print(dt)
print(time.strftime('%Y-%m-%d %H:%M:%S', dt))

# 返回所指向的文件或者目录的最后修改时间

s_file = os.path.join(s_dir, 'files/test.txt')

os.path.getmtime(s_file)

# 返回所指向的文件或者目录的最后修改时间
# 使用 time.ctime() 方法来格式化日期

import time, os

s_file = os.path.join(s_dir, 'files/test.txt')

time.ctime(os.path.getmtime(s_file))

# 返回规范化的绝对路径
# 会自动补齐完整路径,不管文件是否存在

os.path.abspath('tt1211.txt')

# 如果输入是绝对路径，返回True

print(os.path.isabs('test.txt'))
print(os.path.isabs('/Users/yijun/test.txt'))

# 返回一个路径的目录名和文件名

# os.chdir('/Users/david.yi/Documents/dev/python_study/python_basic')
# os.chdir('C:\\Users\\yimeng.zhang\\Desktop\\Class\\python基础\\python_basic')
s_dir = os.getcwd()
s_file = os.path.join(s_dir, 'test.txt')
print(s_file)

# 分拆路径和文件名
os.path.split(s_file)

# 返回路径的目录，其实就是...


I am working on the file "Python 基础课程/Python Basic Lesson 07 - 文件目录操作.ipynb".
The first task is:
我们在 fishbase 的 fish_file 包内，也实现了一个搜索文件的功能，也使用了 python 自带的 pathlib 函数包。
Can you write Python code for it?

# v1.0.14 edit by Hu Jun, edit by Jia Chunying, #38
# v1.0.17 edit by Hu Jun, #212
# v1.3 edit by David Yi, #272
def find_files(path, exts=None):
    """
    查找路径下的文件，返回指定类型的文件列表

    :param:
        * path: (string) 查找路径
        * exts: (list) 文件类型列表，默认为空

    :return:
        * files_list: (list) 文件列表

    举例如下::

        print('--- find_files demo ---')
        path1 = '/root/fishbase_issue'
        all_files = find_files(path1)
        print(all_files)
        exts_files = find_files(path1, exts=['.png', '.py'])
        print(exts_files)
        print('---')

    执行结果::

        --- find_files demo ---
        ['/root/fishbase_issue/test.png', '/root/fishbase_issue/head.jpg','/root/fishbase_issue/py/man.png'
        ['/root/fishbase_issue/test.png', '/root/fishbase_issue/py/man.png']
        ---

        """
    files_list = []
    for root, dirs, files in os.walk(path):
        for name in files:
            files_list.append(os.path.join(root, name))

    if exts is not None:
        return [file for file in files_list if pathlib.Path(file).suffix in exts]

    return files_list


I am working on the file "Python 基础课程/Python Basic Lesson 07 - 文件目录操作.ipynb".
The first task is:
文件和目录操作之二
读写文件是最常见的IO操作。Python内置了读写文件的函数。
读写文件前，我们先必须了解一下，在磁盘上读写文件的功能都是由操作系统提供的，现代操作系统不允许普通的程序直接操作磁盘，所以，读写文件就是请求操作系统打开一个文件对象，然后，通过操作系统提供的接口从这个文件对象中读取数据，或者把数据写入这个文件对象。
读文件
函数 open() 返回 文件对象，通常的用法需要两个参数：open(filename, mode)。分别是文件名和打开模式
在做下面的例子前，我们要创建一个 test.txt 文件，并且保证其中的内容是如下样式，包含三行内容：

hello
hi
byebye

文件保存在可以访问的目录，我们用到的文件都保存在 notebook 下面的 files 目录；

使用 jupyter 可以直接新建 Text File，来完成建立和编辑文本文件
Can you write Python code for it?

import os

# 获得当前路径
s_dir = os.getcwd()

print(s_dir)

# 拼接完整文件名
filename = os.path.join(s_dir, 'files/test.txt')

print(filename)

# 和读写文件打交道是一件需要小心的事情，这里用了 try-finally 的方式来避免出错
try:
    # 打开文件
    f = open(filename, 'r')
    print(f.read())
finally:
    if f:
        f.close()

# 简化调用方式
# 省却了 try...finally，会有 with 来自动控制保证可以关闭文件等

with open(filename, 'r') as f:
    print(f.read())

# 读入文件所有的内容
# 这样操作对于一般的文件没啥问题，太大的文件不能这样读，内存会不够

with open(filename, 'r') as f:
    lines = f.readlines()

print(type(lines))
print(lines)

# 把读入的文件显示出来

for i in lines:
    print(i)

# 更简单的按行读取文件内容方法

with open(filename, 'r') as f:
    for eachline in f:
        print(eachline)


I am working on the file "Python 基础课程/Python Basic Lesson 08 - 函数.ipynb".
The first task is:
写一个函数，输入一个数字，判断其是否是偶数，是偶数的话，返回 True，反之返回 False
写一个函数，输入一个英文单词，返回其中的元音字母的个数
Can you write Python code for it?

# 判断奇偶数

a = int(input('Input a number:'))

def oushu():
    if int(a/2) == a/2:
        return True
        #print('这是个偶数')
    else:
        return False
        #print('这是个奇数')

result = oushu()
print(result)

# 判断元音

def reason(s):
    b = ['a','e','i','o','u']
    c = 0
    for i in list(s):
        if i in b:
            # c=c+1 的简约写法
            c += 1
    return c

a = input('plese input a word:')
print(reason(a))

# 计算一个正整数的因数

def yinshu(number):
    b = []
    for i in range(1,number+1):
        if number % i == 0:
            b.append(i)
    return b

print(yinshu(10))

# 找到最大数 #1

def find_max(list1):

    # max = float('-inf') 表示负无穷大
    max = float('-inf')
    for x in list1:
        if x > max:
            max = x
    return max

print(find_max([-20,1,6,7,20,5]))
print(find_max([-20,-3,-6,-7,-5]))

# 找到最大数 #2
# 使用递归，递归是编程中非常有效的一种解决问题的方式，将内在逻辑分解为一个固定的逻辑，而调用参数来自于上一次的执行结果
# 使用递归要注意初始化和防止递归陷入死循环
# 排序、斐波那契数列这些都是递归的经典实现

def find_max(list1):
    if len(list1) == 1:
        return list1[0]
    v1 = list1[0]
    v2 = find_max(list1[1:])
    if v1 > v2:
        return v1
    else:
        return v2

print(find_max([1,6,7,20,5]))


I am working on the file "Python 基础课程/Python Basic Lesson 08 - 函数.ipynb".
The first task is:
如果上面的函数要修改成只有一个 return 应该怎么修改呢？
Can you write Python code for it?

def my_max(a,b):
    if a > b:
        c = a
    else:
        c = b

    return c

print(my_max(3,6))

# *number 这样的写法，可以理解为传入任意数目个参数，包括0个参数，就是在参数名称前面加上一个 *
# 为了简化程序逻辑，返回的结果现在是假的，后面我们会再修改

def my_max(*number):
    print(type(number))
    return 100

print(my_max(1,5,30,14,25))

# 用列表来排序，来完成这个取得任意值的最大值的函数

def my_max(*number):
    a_list = list(number)
    a_list.sort()
    a = a_list[-1]
    return a

print(my_max(1,5,30,14,25))

# Python的函数返回多值其实就是返回一个tuple，但语法上可以省略括号，写起来更方便

# 同时返回最大值和最小值

def my_max_min(*number):
    a_list = list(number)
    a_list.sort()
    my_max = a_list[-1]
    my_min = a_list[0]
    return my_max, my_min

print(my_max_min(1,5,30,14,25))


I am working on the file "Python 基础课程/Python Basic Lesson 08 - 函数.ipynb".
The first task is:
思考一下

写一个简单的剪刀石头布的游戏；
Can you write Python code for it?

# 简单的剪刀石头布

import random

FIRST = 0
SECOND = 1
BOTH = 2

t1 = ('剪刀', '石头', '布')
t2 = ('human win', 'computer win', 'draw')

def which_win(i1, i2):
    if i1 == 0 and i2 == 1:
        return SECOND
    if i1 == 0 and i2 == 2:
        return FIRST
    if i1 == 1 and i2 == 0:
        return FIRST
    if i1 == 1 and i2 == 2:
        return SECOND
    if i1 == 2 and i2 == 0:
        return SECOND
    if i1 == 2 and i2 == 1:
        return FIRST
    if i1 == i2:
        return BOTH

print('0:剪刀 1:石头 2:布')
human = int(input('你出了:'))

c_index = random.randint(0,2)
computer = t1[c_index]

print("电脑出了",computer)

print(t2[which_win(human, c_index)])

# 优化的剪刀石头布程序

import random

FIRST = 0
SECOND = 1
BOTH = 2

t1 = ('scissors', 'stone', 'cloth')
t2 = ('human win', 'computer win', 'draw')

table = {'01':1, '02':0, '10':0, '12':1, '20':1, '21':0, '00':2, '11':2, '22':2}

def which_win(i1, i2):
    s = i1 + i2
    return table.get(s)

# 显示规则
for i, s in enumerate(t1):
    print(i, s, ', ', end='')

human = input('please input:')
h_index = int(human)
human_choice = t1[h_index]

c_index = random.randint(0,2)
computer_choice = t1[c_index]

print('human:',h_index,human_choice)
print('computer:',c_index, computer_choice)
print(t2[which_win(str(h_index), str(c_index))])

# 五局三胜的剪刀石头布程序

import random

FIRST = 0
SECOND = 1
BOTH = 2

t1 = ('scissors', 'stone', 'cloth')
t2 = ('human win', 'computer win', 'draw')

table = {'01':1, '02':2, '10':0, '12':1, '20':1, '21':0, '00':2, '11':2, '22':2}

def which_win(i1, i2):
    s = i1 + i2
    return table.get(s)

mark = True
computer_win = 0
human_win = 0

while mark:

    # 显示规则
    for i, s in enumerate(t1):
        print(i, s, ', ', end='')

    human = input('please input:')

    c_index = random.randint(0,2)
    computer = t1[c_index]

    print(c_index, computer)

    who_win = which_win(human, str(c_index))

    if who_win == 0:
        human_win += 1
    if who_win == 1:
        computer_win += 1

    print(t2[which_win(human, str(c_index))])
   ...


I am working on the file "Python 基础课程/Python Basic Lesson 09 - 日期函数.ipynb".
The first task is:
思考一下

计算倒计时，现在距离2021元旦距离现在还有多少天
Can you write Python code for it?

from datetime import datetime

#日期格式转换
newyear = datetime.strptime('2036-06-07', '%Y-%m-%d')
#获取现在的时间
now = datetime.now()
#时间差
timedelta = newyear-now
print(timedelta)
print(timedelta.days)


I am working on the file "Python 基础课程/Python Basic Lesson 09 - 日期函数.ipynb".
The first task is:
日期库-字符串和日期的转换
字符串转化为日期：datetime.strptime()
日期转换为字符串：datetime.strftime()
日期字符串格式，举例
python
cday1 = datetime.now().strftime('%a, %b %d %H:%M')
cday2 = datetime.now().strftime('%A, %b %d %H:%M, %j')
cday3 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
日期库 – 日期格式说明

%a 英文星期的简写 (shorthand of week in English)
%A 英文星期的完整拼写 (longhand of week in English)
%b 英文月份的简写 (shorthand of month in English)
%B 英文月份的完整拼写 (longhand of month in English)
%c 本地当前的日期与时间 (current local date and time)
%d 日期数, 1-31之间 (date, between 1-31))
%H 小时数, 00-23之间 (hour, between 00-23))
%I 小时数, 01-12之间 (hour, between 01-12)
%m 月份, 01-12之间 (month, between 01-12)
%M 分钟数, 01-59之间 (minute, 01-59)
%j 本年从第1天开始计数到当天的天数 (total days from 1st day of this year till now)
%w 星期数, 0-6之间(0是周日)  (day of the week, between 0-6, 0=Sunday)
%W 当天属于本年的第几周,周一作为一周的第一天进行计算 (week of the year, starting with Monday )
%x 本地的当天日期 (local date)
%X 本地的当前时间 (local time)
%y 年份,0-99之间 (year, between 0-99)
%Y 年份的完整拼写 (longhand of year)
Can you write Python code for it?

# 字符串转化为日期

day1 = datetime.strptime('2017-1-2 18:19:59', '%Y-%m-%d %H:%M:%S')
print(day1)
print(type(day1))

# 日期转换为字符串

day1 = datetime.now().strftime('%Y, %W, %m %d %H:%M')
print(day1)
print(type(day1))

# 日期转换为字符串，各种格式

cday1 = datetime.now().strftime('%a, %b %d %H:%M')
cday2 = datetime.now().strftime('%A, %b %d %H:%M, %j')
cday3 = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(cday1)
print(cday2)
print(cday3)

# 本地时间转换为字符串

t1 = time.localtime()
print(t1)

t2 = time.strftime('%Y-%m-%d %H:%M:%S',t1)
print(t2)
print(type(t2))


I am working on the file "Python 基础课程/Python Basic Lesson 10 - 函数参数和匿名函数.ipynb".
The first task is:
匿名函数
Python 允许用 lambda 关键字创造匿名函数。
lambda 匿名函数不需要常规函数的 def 和 return 关键字，因为匿名函数代码较短，因此适用于一些简单处理运算的场景。
Can you write Python code for it?

# 等价的函数一般写法和匿名函数写法

def add(x, y):
    return x + y

a = lambda x, y: x + y
a(1,2)

# lambda 同样可以有默认参数

a =  lambda x, y=2 : x + y
a(3)

a(3, 5)

a = lambda x : x * x +40

print(a(2))


I am working on the file "Python 基础课程/Python Basic Lesson 10 - 函数参数和匿名函数.ipynb".
The first task is:
匿名函数的用法特点

只用一次的场景，不用取名称，因为给函数取名是比较麻烦的一件事；
函数逻辑简单，使用匿名函数前确认 Python 没有自带类似功能的函数，实际开发中，不要去重复发明轮子；

思考一下
函数可变参数练习，参数 kind 中增加 max 这个key，如果设置为 ignore，则输入的数字中的最大数忽略
Can you write Python code for it?

# kind 中 增加 max key，
# max = ingnore， 则忽略最大值
def cal_6(*numbers, **kind):

    if 'kind' in kind:
        kind_value = kind.get('kind')

    if 'max' in kind:
        if kind.get('max') == 'ignore':
            numbers = list(numbers)
            numbers.remove(max(numbers))

    n = 0
    for i in numbers:
        n = n + i

    if kind_value == 'avg':
        return n / len(numbers)
    if kind_value == 'sum':
        return n

print(cal_6(1,2,3,4, kind='avg', max='ignore',min='ignore'))
print(cal_6(1,2,3,4, kind='avg'))
print(cal_6(1,2,3,4, kind='sum'))

# kind 中 增加 min key，
# min key = double, 则最小值计算两次

def cal_7(*numbers, **kw):

    numbers = list(numbers)

    if 'kind' in kw:
        kind_value = kw.get('kind')

    if 'max' in kw:
        if kw.get('max') == 'ignore':
            numbers.remove(max(numbers))

    if 'min' in kw:
        if kw.get('min') == 'double':
            numbers.append(min(numbers))

    n = 0
    for i in numbers:
        n = n + i

    if kind_value == 'avg':
        return n / len(numbers)
    if kind_value == 'sum':
        return n

print(cal_7(1,2,3,4, kind='avg', max='ignore', min='double'))
print(cal_7(1,2,3,4, kind='avg'))
print(cal_7(1,2,3,4, kind='sum'))


I am working on the file "Python 基础课程/Python Basic Lesson 11 - 集合库 collections.ipynb".
The first task is:
Counter
Counter是一个简单的计数器，例如，统计字符出现的个数：
Can you write Python code for it?

# Counter类的目的是用来跟踪值出现的次数,以字典的键值对形式存储，其中元素作为key，其计数作为value
# 下面这个例子就是使用 Counter 模块统计一段句子里面所有字符出现次数

from collections import Counter

s = 'A Counter is a dict subclass. '.lower()

c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))

# 是否可以统计中文呢？

s = '他会自己长大远去我们也各自远去'

c = Counter(s)

print(c.most_common(5))

# Counter 举例，用户输入内容

from collections import Counter

s = input('Please input:')

s = s.lower()

c = Counter(s)
# 获取出现频率最高的5个字符
print(c.most_common(5))

# 读出 Counter 对象中的key 和value

s = 'A Counter is a dict subclass. '.lower()
c = Counter(s)

# 用列表生成式获得 counter 中的 key
list1 = [k for k,v in c.most_common()]

# 用列表生成式获得 counter 中的 value
list2 = [v for k,v in c.most_common()]
print(list1)
print(list2)

# 我们在 notebook 中画个图

import matplotlib.pyplot as plt

plt.bar(range(len(list2)), list2,color='rgb',tick_label=list1)
plt.show()


I am working on the file "Python 基础课程/Python Basic Lesson 11 - 集合库 collections.ipynb".
The first task is:
OrderedDict
使用 dict 字典时，Key 是无序的。在对 dict 做迭代访问时，我们无法确定 Key 的顺序。
如果要保持 Key 的顺序，可以用 OrderedDict，这是一个 Key 值有序的字典数据类型。

2020.4.30 从 Python 3.7 开始，默认的 dict 是有顺序的，而不是之前版本是乱序的，也就是默认的 dict 就是记住插入的顺序的。所以本节内容意义已经不大了。反过来证明有序字典是一个多么重要的功能点，已经从包中的功能被移植到了主功能中。
Can you write Python code for it?

# dict 是无序的

d = dict([('a', 1), ('b', 2), ('c', 3)])

print(d)

# 传统dict 追加一对 key value

d = dict([('a', 1), ('b', 2), ('c', 3)])

print(d)

d['d'] = 4
print(d)

# 使用 OrderedDict

from collections import OrderedDict

d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3

print(d)

# 使用 OrderedDict, 追加一对 key value
# OrderedDict 的 key 会按照插入的顺序排列，不是 key 本身排序

from collections import OrderedDict

d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3

print(d)

d['d'] = 4
print(d)

# OrderedDict可以实现一个FIFO（先进先出）的dict，当容量超出限制时，先删除最早添加的Key：

from collections import OrderedDict

class LastUpdatedOrderedDict(OrderedDict):

    def __init__(self, capacity):
        super(LastUpdatedOrderedDict, self).__init__()
        self._capacity = capacity

    def __setitem__(self, key, value):
        containsKey = 1 if key in self else 0
        if len(self) - containsKey >= self._capacity:
            last = self.popitem(last=False)
            print('remove:', last)
        if containsKey:
            del self[key]
            print('set:', (key, value))
        else:
            print('add:', (key, value))
        OrderedDict.__setitem__(self, key, value)

d = LastUpdatedOrderedDict(4)
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)

d['d'] = 4
d['e'] = 5
d['f'] = 6
print(d)

# 简化的先进先出Dict

from collections import OrderedDict
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d)

# 3个参数：原始有序字典，容量限制，待插入的key，待插入的value
def update_ordereddict(ordered_dict, len_limit ,key, value):
    if len(ordered_dict) >=0 and len(ordered_dict) < len_limit:
        ordered_dict[key]=value
        return ordered_dict
    else:
        ordered_dict.popitem(last=False)
        ordered_dict[key]=value
        return ordered_dict

# 插入一个新key-value
update_ordereddict(d, 3, 'new_key', 4)


I am working on the file "Python 基础课程/Python Basic Lesson 11 - 集合库 collections.ipynb".
The first task is:
defaultdict
我们都知道，在使用 Python 原生数据结构字典的时候，如果用 d[key] 这样的方式访问，当指定的key不存在时，是会抛出KeyError异常的，也就是发生错误。（可以用 get 方法来避免这样的错误）
如果使用 defaultdict，只要你传入一个默认的方法，那么请求一个不存在的 key 时，便会调用这个方法，使用其结果来作为这个key的默认值。
Can you write Python code for it?

# 标准的字典用法

i = {'name':'David'}
print(i['name'])

# 不存在 key，则会报错

i = {'name':'David'}
print(i['score'])

# defaultdict 举例

from collections import defaultdict

d = defaultdict(lambda: 100)
d['name']='David'
print(d['name'])

# default 返回默认值，不会报错

print(d['score'])
print(d['best_score'])

from collections import defaultdict

d = defaultdict(lambda: '100')
d['name']='David'
print(d['name'])
print(d['score'])


I am working on the file "Python 基础课程/Python Basic Lesson 11 - 集合库 collections.ipynb".
The first task is:
deque
使用 list 存储数据时，按索引访问元素很快，但是插入和删除元素就很慢了，因为 list 是线性存储，数据量大的时候，插入和删除效率很低。
deque 是为了高效实现插入和删除操作的双向列表，适合用于队列和栈。
deque 在插入数据时候速度比 list 快很多，当然这个是相对存在大量数据的 list 而言的。如果你的程序中需要对有百万级别的 list 频繁的在各个位置插入删除数据，那么用 deque 是值得的。
Can you write Python code for it?

# deque 举例

from collections import deque

q = deque(['a', 'b', 'c'])
q.append('x')
q.appendleft('y')

print(q)

# 对比 list 和 deque 的速度

from collections import deque
import time

# list
q0 = [x*x for x in range(10000000)]

# list
a = time.time()
q0.insert(0,88888)
b = time.time()
print(b-a)

# 生成 deque
q1= deque(q0)

# deque
a = time.time()
q1.appendleft(88888)
b = time.time()
print('%2.16f' % (b-a))

from collections import deque

l = ['a','b','c','d']
l = deque(l)
print(l)

# deque rotation

l = ['a','b','c','d','e']
l = deque(l)
l.rotate(2)
print(l)
l.rotate(-2)
print(l)

# deque pop() 同样可以区分头尾

l = deque(['a','b','c'])
l.pop()
print(l)

# 删除左边的元素

l = deque(['a','b','c'])
l.popleft()
print(l)


I am working on the file "Python 基础课程/Python Basic Lesson 12 - 列表生成式.ipynb".
The first task is:
列表生成式用法
写列表生成式时，把要生成的元素 x * x 放到前面，后面跟 for 循环，就可以把 list 创建出来，十分有用。
在列表生成式后面还可以加上判断，过滤出结果为偶数的结果
[x * x for x in range(1, 11) if x % 2 == 0]
Can you write Python code for it?

# 在列表生成式后面加上判断，过滤出结果为偶数的结果

[x * x for x in range(1, 11) if x % 2 == 0 ]

# 可以在列表生成式中使用双重循环
# 输出一对元组，每个数在10以内，且加在一起等于5

list1 = [(x, y) for x in range(10) for y in range(10) if x + y == 5 if x > y]

print(list1)

# 改进之前寻找目录下指定字母开头的文件的判断方式
# 修改为使用列表生成式

import os

# 可以判断各类情况，比如第一个是大写的 P 字母, 用列表生成式的方式，代码精简了很多
list1 =  [x for x in os.listdir('/Users/yijun') if x[0] == 'P']
print(list1)


I am working on the file "Python 基础课程/Python Basic Lesson 13 - 完整的 for 语句结构和 pprint.ipynb".
The first task is:
pprint() 介绍
pprint module提供了可以按照某个格式正确的显示 Python 已知类型数据的一种方法，这种格式很易读。
Can you write Python code for it?

import sys
print(sys.path)

import sys
import pprint
pprint.pprint(sys.path)

# jupyter notebook 中直接显示一些变量的结果就和采用了 pprint 的方法

import sys
sys.path

# 实际上对 list 类型比较优雅的处理

import sys
print(type(sys.path))


I am working on the file "Python 基础课程/Python Basic Lesson 13 - 完整的 for 语句结构和 pprint.ipynb".
The first task is:
如果你对使用 python 来构造一种语言，比如适用一些场景的 DSL 感兴趣，如果你觉得 lex 和 yacc 这些编译原理中的概念感兴趣的话，可以参考python ply包作者的网站：https://www.dabeaz.com/software.html
Python 下有很多优秀的包，都可以来实现语言定义和解析，但是 ply 是其中最经典的包，从2001年诞生至今，一致在维护更新，并且不断发展。
下面这个是 ply 自己带的例子，用来实现一个比较完整的计算器。因为是通过语法分析的方式实现，会比较费解，但是功能强大，并且容易扩充。
Can you write Python code for it?

# -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables -- all in one file.
# -----------------------------------------------------------------------------

tokens = (
    'NAME', 'NUMBER',
    'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'EQUALS',
    'LPAREN', 'RPAREN',
)

# Tokens

t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_EQUALS = r'='
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'

def t_NUMBER(t):
    r'\d+'
    try:
        t.value = int(t.value)
    except ValueError:
        print("Integer value too large %d", t.value)
        t.value = 0
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex

lexer = lex.lex()

# Parsing rules

precedence = (
    ('left', 'PLUS', 'MINUS'),
    ('left', 'TIMES', 'DIVIDE'),
    ('right', 'UMINUS'),
)

# dictionary of names
names = {}

def p_statement_assign(t):
    'statement : NAME EQUALS expression'
    names[t[1]] = t[3]

def p_statement_expr(t):
    'statement : expression'
    print(t[1])

def p_expression_binop(t):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if t[2] == '+':
        t[0] = t[1] + t[3]
    elif t[2] == '-':
        t[0] = t[1] - t[3]
    elif t[2] == '*':
        t[0] = t[1] * t[3]
    elif t[2] == '/':
        t[0] = t[1] / t[3]

def p_expression_uminus(t):
    'expression : MINUS expression %prec UMINUS'
    t[0] = -t[2]

def p_expression_group(t):
    'expression : LPAREN expression RPAREN'
    t[0] = t[2]

def p_expression_number(t):
    'expression : NUMBER'
    t[0] = t[1]

def p_expression_name(t):
    'expression : NAME'
    try:
        t[0] = names[t[1]]
    except...


I am working on the file "Python 基础课程/Python Basic Lesson 13 - 完整的 for 语句结构和 pprint.ipynb".
The first task is:
思考一下
简单的四则运算器，想一下怎么实现。
Can you write Python code for it?

# 简单四则计算器代码，下面代码参考 https://www.jianshu.com/p/c22bfd91df49

def calculate():
     operation = input('''
     please type in the math operation you would like to complete:
     + for addition
     - for subtraction
     * for multiplication
     / for division
     ''')
     number_1 = float(input('Please enter the first number: '))
     number_2 = float(input('Please enter the second number: '))
     if operation == '+':
          print('{} + {} = {} '.format(number_1, number_2,number_1 + number_2))

     elif operation == '-':
          print('{} - {} = {} '.format(number_1,number_2,number_1 - number_2))
     elif operation == '*':
          print('{} * {} = {} '.format(number_1, number_2,number_1 * number_2))
     elif operation == '/' and number_2 != 0:
          print('{} / {} = {} '.format(number_1, number_2,number_1 / number_2))
     else:
          print('You have not typed a valid operator, please run the program again.')

calculate()


I am working on the file "Python 基础课程/Python Basic Lesson 14 - 访问网络.ipynb".
The first task is:
下载文件
使用requets 可以很方便的获得网站中的图片、文件等。下面只是简单的举例，下载 baidu 的 logo 文件。
Can you write Python code for it?

# 下载文件 使用 requests
# baidu 的 logo 文件： http://home.baidu.com/resource/r/home/img/logo-yy.gif

import requests

url = 'http://home.baidu.com/resource/r/home/img/logo-yy.gif'

r = requests.get(url)
with open("files/baidu_logo.gif", "wb") as code:
    code.write(r.content)
    print('download ok')


I am working on the file "Python 基础课程/Python Basic Lesson 16 - 函数式编程.ipynb".
The first task is:
filter() 函数
Python内建的filter()函数用于过滤序列。
和map()类似，filter()也接收一个函数和一个序列。和map()不同的是，filter()把传入的函数依次作用于每个元素，然后根据返回值是True还是False决定保留还是丢弃该元素。
Can you write Python code for it?

# filter 举例，在一个list中，删掉偶数，只保留奇数

# 判断是否是奇数
def is_odd(n):
    return n % 2 == 1

print(list(filter(is_odd, [1, 2, 4, 5, 6])))

# 筛选一个 list 中为空的元素

def is_empty(s):
    # strip() 用于移除字符串头尾指定的字符（默认为空格）
    if len(s.strip()) ==0:
        return False
    else:
        return True

print(list(filter(is_empty, ['A', '', 'B','C', '  '])))

# 返回一定范围内既不能被2整除也不能被3整数的数字

def f(x):
    return x % 2 != 0 and x % 3 != 0

print(list(filter(f, range(2, 30))))


I am working on the file "Python 基础课程/Python Basic Lesson 16 - 函数式编程.ipynb".
The first task is:
reduce() 函数
再看 reduce 的用法。reduce 把一个函数作用在一个序列[x1, x2, x3, ...]上，这个函数必须接收两个参数，reduce 把结果继续和序列的下一个元素做累积计算，其效果就是：
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
Can you write Python code for it?

# reduce 举例，一个加法函数
from functools import reduce

def add(x, y):
    return x + y

print(reduce(add, [1, 3, 5, 7, 9]))

# reduce，模拟一个字符串转换为整数的函数

from functools import reduce

def f(x, y):
    return x * 10 + y

def char2int(s):
    return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
            '6': 6, '7': 7, '8': 8, '9': 9}[s]

def str2int(s):
    return reduce(f, map(char2int, s))

print(str2int('13579'))
print(type(str2int('13579')))

# 拆解上面的函数，先 map

list1 = map(char2int, '13579')
for i in list1:
    print(i,type(i))

# 拆解上面的函数，再 reduce

list1 = map(char2int, '13579')
print(reduce(f,list1))


I am working on the file "Python 基础课程/Python Basic Lesson 16 - 函数式编程.ipynb".
The first task is:
虽然默认参数还是很容易使用，但是如果我们在某个场景需要大量调用的话，还是有点不方便，特别是对于有很多参数的函数来说，会让程序显得复杂。还记得之前那个 max min 的程序举例么？我们可以用偏函数来解决整个问题。
通过 functools.partial 来进行操作。
Can you write Python code for it?

import functools

int2 = functools.partial(int, base=2)

print(int2('1000000'))
print(int2('1010101'))

# 偏函数举例
# 原来的一个函数

def func(x=2,y=3,z=4):
    return x+y+z

print(func(x=3))
print(func(y=6))
print(func(x=4,y=10))
print(func(2,3))

# 构造偏函数，设置默认值

import functools

f1 = functools.partial(func, x=2,z=3)
print(f1(y=3))
print(f1(y=2))
print(f1(2)) # 会报错，不需要再输入 z 的值


I am working on the file "Python 基础课程/Python Basic 练习题A.ipynb".
The first task is:
题目2：输出 9*9 乘法口诀表
程序分析：分行与列考虑，共9行9列，i控制行，j控制列。
Can you write Python code for it?

for i in range(1, 10):
    for j in range(1, i+1):
        print ("%d x %d = %d" % (i, j, i*j),"\t",end="")
        if i==j:
            print("")

i=0
j=0
while i<9:
    i+=1
    while j<9:
        j+=1
        print(j,"x",i,"=",i*j,"\t",end="")
        if i==j:
            j=0
            print("")
            break

print('\n'.join(['\t'.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))


I am working on the file "Python 基础课程/Python Basic 练习题A.ipynb".
The first task is:
题目3：编写一个函数，给你三个整数a,b,c, 判断能否以它们为三个边长构成三角形。若能，输出YES，否则输出NO
Can you write Python code for it?

def func1(a,b,c):
    if (a+b)>c and (b+c)>a and (a+c)>b:
        return 'yes'
    else:
        return 'no'

print(func1(1,2,3))

def func2(a,b,c):
    if max(a,b,c)<(a+b+c)/2.0:
        return 'yes'
    else:
        return 'no'

print(func2(3,4,5))

# if else 的用法

x, y = 4, 5

smaller = x if x > y else y

print(smaller)

# 匿名函数 lambda 用法

a =  lambda x, y=2 : x + y*3
print(a(3) + a(3, 5))

# list 的 count方法

l = ['tom', 'steven', 'jerry', 'steven']
print(l.count('tom') + l.count('steven'))

# os 用法
# 计算目录下有多少文件

import os

a = os.listdir()
print(len(a))

# 获得路径或者文件的大小
import os

os.path.getsize('/Users')

# 列表生成式用法
# 在列表生成式后面加上判断，过滤出结果为偶数的结果

n = 0
for i in [x * x for x in range(8, 11) if x % 2 == 0]:
    n = n + i
print(n)

# 简化调用方式
# 省却了 try...finally，会有 with 来自动控制

filename = 'test.txt'

with open(filename, 'r') as f:
    print(f.read())

# python 有趣灵活的变量定义

first, second, *rest = (1,2,3,4,5,6,7,8)
print(first + second + rest[2])

# for continue 举例
# 以及 等于 不等于 或者 的逻辑判断

for l in 'computer':
    if l != 't' or l == 'u':
        continue
    print('letter:', l)

# 找到符合 x*x + y*y == z*z + 3 的 x y z
# 多种循环

n = 0

for x in range(1,10):
    for y in range(x,10):
        for z in range(y,10):
            if x*x + y*y == z*z:
                print(x,y,z)
                n= n + 1
print('count:',n)

# python 内置函数

print(max((1,2),(2,3),(2,4),(2,4,1)))

l = ['amy', 'tom', 'jerry ']
for i, item in enumerate(l):
    print(i, item)

# question 1
l = [ x * 2 + 3  for x in range(1, 11)]
print(l)
print(l[1]+l[3])

# question 2

import os

os.getcwd()

# question 3

first, second, *rest = (1,2,3,4,5)
print(*rest)

# question 4

from collections import deque

q = deque(['a', 'b'])
q.appendleft('b','a')

print(q.count('b'))

# question 5

x, y = 3, 6

if 1 < x < 4 < y:
    print('yes')
else:
    print('no')

# question 6

d = dict([('a', 1), ('b', 2)])
print(d.get('a',2))

# question 7

a = [0, 1, 2, 3, 4, 5]
n = 0
for i in a[::-2]:
    n=n+i
print(n)

# question 8

a = ['a', '-', 'a']
print('-'.join(a))

# quesion...


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
init() 构造器方法和 del() 解构器方法
可以理解构造就是创建，解构就是销毁。每一个对象的实例都是有声明周期的，从构造到解构。
类别调用的时候，对象被创建的时候，python 先检查是否实现了 init() 方法，如果没有，则什么也不干。如果有 init()方法，则执行。
python 作为高级语言，具有垃圾对象回收机制，当 python 发现对于该实例对象的引用都被清除掉后，会执行 del() 方法。通常不需要自己去实现这个 del() 方法，python 会做好这一切。
Can you write Python code for it?

# 先整理一下上面的代码
# v1.0.1

# NPC 类
class NPC(object):

    # 初始化 NPC 的属性
    def __init__(self, name):
        self.name = name
        self.weapon = 'gun'
        self.blood = 1000

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)

    # 定义方法 - 通用攻击
    def fight_common(self):
        print('Fight Common')

# 战士 Soldier 类
class Soldier(NPC):

    # 建立 soldier 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.soldier_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        # 通过 super 来调用父类方法
        super(Soldier, self).show_properties()
        print('soldier_level', self.soldier_level)

# 创建两个 soldier

n1 = Soldier('AA1')
n1.show_properties()
n1.fight_common()

print()

n2 = Soldier('AA2')
n2.show_properties()
n2.fight_common()

# 连续创建多个 soldier 的实例
# 并存储在 list 中

s = []

for i in range(3):
    n = Soldier('AA' + str(i))
    n.show_properties()
    n.fight_common()
    s.append(n)

# 看一下存储了对象的列表

print(s)

# 可以和一般访问列表一样访问列表中的对象

for i in s:
    print(i.name)

print(len(s))

# 可以删除一个实例
s.pop(1)

# 显示列表中的实例
for i in s:
    print(i.name)

print(len(s))

# 再增加一个巫师 Wizard 的类

# 巫师 Wizard 类
class Wizard(NPC):

    # 建立 Wizard 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.wizard_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        # 通过 super 来调用父类方法
        super(Wizard, self).show_properties()
        print('wizard_level', self.wizard_level)

    # 定义一个巫师专用的战斗方法
    def wizard_fight_magic(self):
        print('Wizard Magic!')

# 创建一个 wizard

c1 = Wizard('CC1')
c1.show_properties()
c1.fight_common()
c1.wizard_fight_magic()

# 创建复杂的 NPC，3个 wizards，3个 soldiers

# 创建多个 soldier 的实例
s = []

for i in range(3):
    n =...


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
再来看看 show_properties() 这个方法，总感觉这样有点笨重，因为不管是否是面向对象的编程方式，都不应该有太多重复的代码，现在 NPC 类中也有 show_properties() 方法，用来显示标准的三个属性，而 Soldier 类中同样名字的方法显示四个属性，如果 NPC 类中增加了属性，那么两边类中的这个方法都要修改。
我们来看看有没有更好的办法，可以用 super(需要知道父类的类，self) 的方法来访问父类的方法，这样代码就简洁优雅了。
Can you write Python code for it?

# 战士 Soldier 类
class Soldier(NPC):

    # 建立 soldier 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.soldier_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        # 通过 super 来调用父类方法
        super(Soldier, self).show_properties()
        print('soldier_level', self.soldier_level)

# 创建一个 Soldier 类， 作为 NPC 的子类
n1 = Soldier('AA2')
n1.show_properties()
n1.fight_common()


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
在子类中，可以覆盖父类的方法。
比如 __init__() ，我们需要在 Soldier 类的初始化中加入一个只有 soldier 才有的级别 level 属性。
所以，我们先调用父类的__init__() 方法，再写 Soldier 类需要的代码。
而 show_properties()方法，我们先用简单的办法，完全覆盖，也就是使用这个新的show_properties()方法，来显示 NPC 标准的三个属性以及 Soldier 的一个独立属性。
Can you write Python code for it?

# 战士 Soldier 类
class Soldier(NPC):

    # 建立 soldier 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.soldier_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)
        print('soldier_level:', self.soldier_level)

# 创建一个 Soldier 类， 作为 NPC 的子类
n1 = Soldier('AA2')
n1.show_properties()
n1.fight_common()


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
类的方法
光是把类作为命名空间太简单了，可以给类添加功能，称为方法。
方法定义在类中，使用在实例中。可以理解为实例是真正做事情的代码，所以在实例中调用方法完成某个功能是合理的。
Can you write Python code for it?

class MyData(object):

    # 定义一个 SayHello 的方法，self 可以理解为必须传递的参数
    def SayHello(self):
        print('Hello!')

# 实例化
obj_math = MyData()

# 调用方法
obj_math.SayHello()

# 类的方法的直接调用，其实还是实例化了

MyData().SayHello()

# 在上面基础上，复杂一点的例子

class MyData(object):

    # 初始化方法，双下划线前后
    # 实例化的时候，需要传递 self 之后的参数
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # 定义一个 SayHello 的方法，self 可以理解为必须传递的参数
    def SayHello(self):
        print('Hello!')

    def Add(self):
        print(self.x + self.y)

# 实例化
obj_math = MyData(3,4)

# 调用方法
obj_math.SayHello()

obj_math.x = 5

obj_math.Add()

o1 = MyData(1,3)
o1.Add()

# 再复杂一点，创建多个实例

class MyData(object):

    # 初始化方法，双下划线前后
    # 实例化的时候，需要传递 self 之后的参数
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # 定义一个 SayHello 的方法，self 可以理解为必须传递的参数
    def SayHello(self):
        print('Hello!')

    def Add(self):
        print(self.x + self.y)

# 实例化
obj_math = MyData(3,4)

# 调用方法
obj_math.SayHello()
obj_math.Add()

# 再创建一个实例
obj_math2 = MyData(5,6)
obj_math2.Add()

# 我们建立一个有趣的简单的模仿游戏的类来说明面向对象编程的概念
# v1.0.0

# NPC 类
class NPC(object):

    # 初始化 NPC 的属性
    def __init__(self, name):
        self.name = name
        self.weapon = 'gun'
        self.blood = 1000

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)

    # 定义方法 - 通用攻击
    def fight_common(self):
        print('Fight Common')

n1 = NPC('AA1')
n1.show_properties()
n1.fight_common()


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
这个 NPC 的类，在初始化这里定义了 NPC 拥有的三个属性，name、weapon、blood，其中 name 需要创建实例的时候设置。
NPC 类有两个方法，一个是 show_properties()，显示 NPC 的属性；另外一个是 fight_common()，我们称之为普通攻击。
创建和使用子类
通过 class B(A)，即表示从 A 开始创建一个子类，我们称之为继承。
面向对象的编程方式的有点已经可以体现，我们可以通过继承来构造一个对象体系，比如这里现在 NPC 这个类中，定义了游戏中人物的最基本的一些属性和方法，可以理解不光 NPC 是战士，还是巫师，对会有这些属性和方法；然后我们把各自独特的属性和方法定义在从 NPC 中继承的各个子类中。我们先来定义一个战士 Soldier 类。
Can you write Python code for it?

# 战士 Soldier 类，继承自 NPC class
class Soldier(NPC):
    # 暂时什么也不干
    pass

# 创建一个 Soldier 类， 作为 NPC 的子类
n1 = Soldier('AA2')

# 调用方法，因为 Soldier 中此刻并没有任何实际的方法等，所以实际上自动调用了父类的方法
n1.show_properties()
n1.fight_common()


I am working on the file "Python 基础课程/draft/python_basic_2/Python - 面向对象编程 01.ipynb".
The first task is:
面向对象程序设计（英语：Object-oriented programming，缩写：OOP）是种具有对象概念的程序编程范型，同时也是一种程序开发的方法。它可能包含数据、属性、代码与方法。对象则指的是类的实例。它将对象作为程序的基本单元，将程序和数据封装其中，以提高软件的重用性、灵活性和扩展性，对象里的程序可以访问及经常修改对象相关连的数据。在面向对象程序编程里，计算机程序会被设计成彼此相关的对象。
面向对象程序设计可以看作一种在程序中包含各种独立而又互相调用的对象的思想，这与传统的思想刚好相反：传统的程序设计主张将程序看作一系列函数的集合，或者直接就是一系列对电脑下达的指令。面向对象程序设计中的每一个对象都应该能够接受数据、处理数据并将数据传达给其它对象，因此它们都可以被看作一个小型的“机器”，即对象。目前已经被证实的是，面向对象程序设计推广了程序的灵活性和可维护性，并且在大型项目设计中广为应用。此外，支持者声称面向对象程序设计要比以往的做法更加便于学习，因为它能够让人们更简单地设计并维护程序，使得程序更加便于分析、设计、理解。反对者在某些领域对此予以否认。
Can you write Python code for it?

# 继续优化，根据 NPC 类型来设定 blood 和 weapon
# 将代码尽量集中，是有好处的
# v1.0.5

# NPC 类
class NPC(object):

    # 初始化 NPC 的属性
    def __init__(self, name):
        self.name = name

        self.npc_type = type(self).__name__

        print('')
        print(self.npc_type, 'NPC created!')

        if self.npc_type == 'Soldier':
            self.weapon = 'sword'
            self.blood = 1000

        if self.npc_type == 'Wizard':
            self.weapon = 'staff'
            self.blood = 2000

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        print('name:', self.name)
        print('weapon:', self.weapon)
        print('blood:', self.blood)

    # 定义方法 - 通用攻击
    def fight_common(self):
        print('Fight Common')

# 战士 Soldier 类
class Soldier(NPC):

    # 建立 soldier 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.soldier_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        # 通过 super 来调用父类方法
        super(Soldier, self).show_properties()
        print('soldier_level', self.soldier_level)

# 巫师 Wizard 类
class Wizard(NPC):

    # 建立 Wizard 的初始化
    def __init__(self, name):
        # 调用 父类 NPC 的初始化方法
        NPC.__init__(self, name)

        # soldier 自己的初始化
        self.wizard_level = 1

    # 定义方法 - 显示 NPC 属性
    def show_properties(self):
        # 通过 super 来调用父类方法
        super(Wizard, self).show_properties()
        print('wizard_level', self.wizard_level)

    # 定义一个巫师专用的战斗方法
    def fight_magic(self):
        print('Wizard Magic!')

s = []

for i in range(2):
    n = Soldier('AA' + str(i))
    n.show_properties()
    s.append(n)

for i in range(2):
    n = Wizard('CC' + str(i))
    n.show_properties()
    s.append(n)


I am working on the file "Python 복습/03일차.금_전처리,클래스/3일차 복습_전처리, 클래스.ipynb".
The first task is:
3의 배수가 입력되면 beer, 5의 배수가 입력되면 chicken, 15의 배수는 beerchicken
Can you write Python code for it?

num = 15
result = ""
if num % 3 == 0:
    result += "Beer"
if num % 5 == 0:
    result += "Chichen"
print(result)

result = []
for i in range(1, 100+1):
    word = ''
    if i % 3 == 0:
        word += "Beer"
    if i % 5 == 0:
        word += "Chicken"
    result.append(word)
print(result)

beer_list = [
    "Beer" if x % 3 == 0 else ""
    for x
    in range(1, 100+1)
]

chicken_list = [
    "Chicken" if x % 5 == 0 else ""
    for x
    in range(1, 100+1)
]

print([
    beer_list[i] + chicken_list[i]
    for i
    in range(100)
])

def word_add_num(count, first_num, first_word, second_num, second_word):
    first_list = [
        first_word if i % first_num == 0 else ""
        for i
        in range(1, count+1)
    ]

    second_list = [
        second_word if i % second_num == 0 else ""
        for i
        in range(1, count+1)
    ]

    return [
        first_list[i] + second_list[i]
        for i
        in range(count)
    ]
#함수이기 때문에 return을 해주어야 한다.

print(word_add_num(100, 3, "ki", 7, "poy"))


I am working on the file "Python 복습/03일차.금_전처리,클래스/3일차 복습_전처리, 클래스.ipynb".
The first task is:
Class ( Rectangle ) => 붕어빵틀, 이데아
객체를 정의해 놓은 것
객체를 생성하기 위해 사용
Object=객체 ( rec1, rec2 ) => 실제 있는 애, 붕어빵, ..
실제로 존재하는 것. 사물 또는 개념
Can you write Python code for it?

class Rectangle():

    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return "면적은 {area} 입니다.".format(
            area=self.width * self.height
        )

    def girth(self):
        return "둘레는 {girth} 입니다".format(
            girth = self.width * 2 + self.height * 2,
        )

    def is_bigger(self, another):
        my_area = self.area()
        another_area = another.area()

        return my_area > another_area

my_rectangle = Rectangle(100, 200)
another_rect = Rectangle(10, 20)
my_rectangle.is_bigger(another_rect)

class Person():

    def __init__(self, name, money):
        self.name = name
        self.money = money

    def send_money(self, to, amount):
        print("{to_name}한테 {amount}원 만큼 돈을 보냅니다.".format(
            to_name=to.name,
            amount=amount,
            ))
        self.money -= amount
        to.money += amount

person1 = Person("돈 빌려준 사람", 1000)
person2 = Person("돈 빌린 사람", 500)

person2.send_money(person1, 500)

person1.money, person2.money

class Student():

    def __init__(self, name, address):
        self.name = name
        self.address = address

    def introduce(self):
        print("저는 {address}에 살고 있는 {name}입니다.".format(
            address=self.address,
            name=self.name,
            ))

student = Student("김기표", "경기도 안양시")
student.introduce()

with open("../users.csv", "r") as f:   #users.csv라는 사용자 정보 있을 때
    student_list = [
        Student(
            line.split(",")[0],
            line.split(",")[1].replace("\n", "")
        )
        for line
        in f.readlines()
    ]
for student in student_list:
    student.introduce()


I am working on the file "Python 복습/03일차.금_전처리,클래스/3일차 복습_전처리, 클래스.ipynb".
The first task is:
Palindrome

거꾸로 해도 같은 단어
기러기 => 기러기, 소주만병만주소 => 소주만병만주소
문자열을 받아서, 뒤집었을 때 같으면 True, 다르면 False
Can you write Python code for it?

def reverse(word):
    reversed_word = ""
    for i in range(len(word)):
        reversed_word += word[len(word)-1-i]
    return reversed_word

def is_palindrome(word):
    return word == reverse(word)

is_palindrome("기러기")

is_palindrome("소주만병만주소")

is_palindrome("김기표")

"자일리톨껌"[::-1]

def reverse(word):
    return word[::-1]

def is_palindrome(word):
    return word == reverse(word)

is_palindrome("기러기")

is_palindrome("PCA")

is_palindrome("ABCBA")

def is_palindrome(word):
    return word == word[::-1]

is_palindrome("수박이박수")

(lambda x: x == x[::-1])("손가방")

(lambda x: x == x[::-1])("고기고")

def word_split(sentence, sperat=" "):
    word_list = []
    word = ""
    for char in sentence:
        if char == " ":
            word_list.append(word)
            word = ""
        else:
            word += char
    return word_list

word_split("오늘은 날씨가 참 맑구나.")

def word_split(sentence, sperat=" "):
    word_list = []
    word = ""
    for char in sentence + " ":   # " " 이거를 추가해야 끝까지 출력이 됩니다.
        if char == " ":
            word_list.append(word)
            word = ""
        else:
            word += char
    return word_list

word_split("오늘은 날씨가 참 맑구나.")

def word_split(sentence, seperate=" "):
    word_list =[]
    word = ""

    for char in sentence:
        if char == " ":
            word_list.append(word)
            word=""
        else:
            word += char
    if word != "":
        word_list.append(word)
    return word_list

word_split("오늘은 날씨가 참 맑구나.")

def word_split(sentence, seperate=" "):
    word_list = []
    word = ""

    for char in sentence:
        if char == seperate:
            word_list.append(word)
            word = ""
        else:
            word += char
    if word != "":
        word_list.append(word)
    return word_list

word_split("오늘은 왠지 날씨가 참 맑은가.", "가")


I am working on the file "Python 복습/03일차.금_전처리,클래스/3일차 복습_전처리, 클래스.ipynb".
The first task is:
절차 지향 프로그래밍: 데이터, 데이터 처리하는 함수
객체 지향 프로그래밍 ( Object Oriented Programming )
절차 <<<< 객체
둥둥 떠다니는 객체
객체(데이터, 각각의 데이터를 처리하는 방법) <=> 객체 : 메시지를 전달

실험 => 완벽하게 적합한 알고리즘

함수형 프로그래밍 => Lambda, Lambda Operator, List Comprehension

객체는 자료형(클래스)를 가진다

모듈은 .py파일 형식. 함수와 변수 선언을 담고 있다. 다른 .py파일에서 추가해서 사용할 수 있다. import로 모듈을 불러올 수 있다.
Can you write Python code for it?

class Student():     # Student() => __init__ 함수가 실행되는 것
    __campus = "패스트캠퍼스"   #변수를 밖에서 부를 수는 있지만 안 부르는 것이 약속

    def __init__(self, name, age):  # init => initialize ( 초기화하다 )
        self.name = name
        self.age = age
        print("학생 {name}({age}) 가 태어났습니다.".format(
            name=self.name,
            age=self.age
        ))

    # 자기소개를 할 수 있다.
    def introduce(self):
        print("안녕하세요, 저는 {campus}에 다녔던 {age}살 {name} 입니다.".format(
            campus=self.__campus,
            age=self.age,
            name=self.name,
        ))

kimkipoy = Student("김기표", 29)

kimkipoy.introduce()

kimkipoy.campus = "경쟁사"
kimkipoy.introduce()

kimkipoy   #_Student__campus 이와 같은 형태로 변수가 바뀌었다.
dir(kimkipoy)

kimkipoy._Student__campus = "경쟁사2"
kimkipoy.introduce()

class Rectangle():
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def girth(self):
        return 2 * (self.width + self.height)

    def is_bigger(self, another):
        if self.area() - another.area() >= 0:
            print("내가 더 큼")
        else:
            print("내가 더 작음")

rec1 = Rectangle(10, 20)
rec2 = Rectangle(30, 10)

rec1.is_bigger(rec2)


I am working on the file "Python 복습/04일차.월_데코레이터, 클래스상속/4일차_과제.ipynb".
The first task is:
2번 문제. replace함수의 구현

문자열을 치환하는 Python 내장 함수인 replace를 직접 구현하세요.
Can you write Python code for it?

"패스트캠퍼스".replace("패스트","Fast")

"웹프로그래밍 스쿨과 데이터 사이언스 스쿨".replace("스쿨", "SCHOOL")


I am working on the file "Python 복습/04일차.월_데코레이터, 클래스상속/4일차_과제.ipynb".
The first task is:
sentence 라는 문자열에서 find_word 를 찾아서 replace_word 로 변환해주는 함수
Can you write Python code for it?

def word_replace(sentence, find_word, replace_word):
    result = ""
    i = 0

    while i < len(sentence):
        is_exist = True
        for j in range(len(find_word)):
            if sentence[i+j] != find_word[j]:
                is_exist = False
                break
        if is_exist:
            result += replace_word
            i += len(find_word)

        else:
            result += sentence[i]
            i += 1
    return result

word_replace("슬로슬로우캠퍼스슬로우","슬로우","slow")

#3번 문제...? 모르겠습니다.
def change_weekday(num):
    change_dic = {
        "0": "월요일",
        "1": "화요일",
        "2": "수요일",
        "3": "목요일",
        "4": "금요일",
        "5": "토요일",
        "6": "일요일",
    }
    for key, value in change_dic.items():
        num = num.replace(key, str(value))

    return num

num = int(calendar.weekday(2016, 5, 8))
change_weekday("3")

#4번 문제...? 모르겠습니다.

histogram = input("문자열을 입력하세요: ")

word_count={}
for word in histogram.replace(',','').split():
    if word in word_count:
        word_count[word]+=1
    else:
        word_count[word]=1

print(word_count)

#5번 문제
how_much = int(input())
def fibonacci(how_much):
    result = ""
    for i in range(how_much):
        result += how_much
    return result


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
Error
실행 자체가 되지 않은 것
문법 자체의 오류가 있어서 SyntaxError ( ParsingError )
Can you write Python code for it?


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
Exception이 뜨면 좋은 것이다. 일단 남이 의도하지 않은 방향대로 뭔가 클래스나 함수, 객체 등을 쓰고 있는 것이기 때문

2T_예외를 처리하는 방법

Exception Handling

예외를 처리하는 방법 => AttributeError, FileNotFoundError, AttributeError, ...

우리가 직접 예외를 만드는 방법(FibonacciShouldGetPositiveNumberError => 우리만의 예외)

Class를 만들어야 한다.
Can you write Python code for it?

NameError

Exception?

def append_string_to_hello(string):
    return "hello, " + string

append_string_to_hello("world")

append_string_to_hello(13)

"hello, " + 3
#str + int, implicit(함축적)한 방법이다.
#Python은 형변환이 되지 않기 때문이다.(형변환 잘 되는 것은 루비)
#자유도가 높거나 해서 좋은 언어는 아니다. 언어 특성에 맞게 사용하면 된다.

"hello" + str(3)
# str + str(int), explicit(명시적)한 방법이다.

awesome_list = ["world", "hello", "python", 5678, "fastcampus"]

for awesome in awesome_list:
    # 예외 처리가 가능한 장소 [1] => 밑에 있는 케이스에서만 예외처리가 가능
    print(append_string_to_hello(awesome))

def append_string_to_hello(string):
    # 예외처리가 가능한 장소(2) => 함수 불렀을 모든 경우에서 예외 처리 가능
    # 그래서 2번에서 해보겠다.
    return "hello, " + string

def append_string_to_hello(string):
    # 예외처리가 가능한 장소
    # 예외처리 => try:-except: (항상 이런 방법으로 한다.)
    try:
        return "hello, " + string
    except TypeError as err:
        print("오류" * 40)

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except TypeError as err:
        #TypeError는 class다. 즉 에러 하나하나 자체는 클래스로 만들어진 에러 객체이다.
        print(err)

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except TypeError as err:
        return err

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except: #이렇게 할 경우 모든 에러에 대해 예외처리. 일반적으로 많이 사용
        return err

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except {TypeError, AttributeError} as err: #이렇게도 쓰나 잘 쓰진 않는다.
        return err

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except TypeError as err:
        #알람을 받을 수 있도록 넣을수도 있다.
        print("send_sms")
        raise

append_string_to_hello(123)

def append_string_to_hello(string):
    try:
        return "hello, " + string
    except TypeError as err:
        print("send_sms")
        raise
    except AttributeError as err:
       ...


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
print를 쓰면 직관적으로 볼 수 있지만 안 좋은 이유는 결과에 영향을 미치기 때문
그리고 특정값만 보고 싶은데 전체를 봐야 하기 때문에
(print는 결과에 영향을 안 미치지 않나?) -> 결과값에 영향이 아니라 output에 영향을 준다는 의미

출력을 하기는 한다. 다만, print로 직접 하지는 않는다.
로그를 쌓는다. ( Log ) -> logging
Can you write Python code for it?

import logging

# logging -> debug, info, warning, danger, critical...
logging.warning("hello world")


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
디버깅? de+bugg+ing => 버그를 잡는다

Jupyter는 Python interpreter이다. 이것을 웹 환경에서 쓸 수 있도록 바꾼 것이 Jupyter Notebook 이다.

예전 이름은 Ipython이었다.
실제 환경(cmd에서 python 입력한 환경)에서는 tap키가 안 된다. 그래서 작성하기 어려운 환경이다.
Jupyter Notebook => Multi-user => Jupyterhub. 주피터 노트북은 멀티유저모드로 주피터허브라고 한다. 여러 사람이 같이 쓸 수 있는 환경
디버깅은 IPython에 내장되어 있는 기능
Can you write Python code for it?

name = "KiPyo Kim"
age = 29

from IPython import embed
embed()

for i in range(3):
    a = i * 7
    b = i + 2
    c = a * b

    embed()

from IPython import embed; embed()   #보통 디버깅 할 때 이렇게 해서 단축키로 지정하고 많이 쓴다.

for i in range(100):
    from IPython import embed; embed()
#이렇게 하면 무한루프에 빠진다. 커널을 종료하는 수밖에...


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
만약 안에 있는 것을 exit()로 종료하지 않고 dd로 밖에서 강제 종료할 경우

계속 돌아가기 때문에 다음 명령어가 *에서 멈춘다. 그래서 노트북을 종료하고 재시작해야 한다.

embed는 IPython 내부에서 IPython을 또 띄운 것

Ipython embed가 디버깅 할 때 가장 많이 사용할 방법이다.일반적으로 사용
Can you write Python code for it?

def fibo(n):
    if n <= 0:
        return 0
    if n == 1:
        return 1
    embed()
    return fibo(n-1) + fibo(n-2)

fibo(5)

class Student():

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        from IPython import embed; embed()
        return (self.name, self.age)

kkp = Student("kipoy", 29)

kkp.introduce()

def fibo(n):
    if n <= 0:
        return 0
    if n == 1:
        return 1
    print("fibo({n}) = fibo({n_1}) + fibo({n-2})".format(n=n, n_1=n-1, n_2=n-2))
    return fibo(n-1) + fibo(n-2)

fibo(3)

fibo(10)


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
상속 순서
object -> Exception -> Fibo...
Can you write Python code for it?

fibo(-1)

raise FibonacciShouldNotHaveNegativeNumberError()
# 다른 에러들은 수정 요구 사항까지 나온다.

"hello, " + 5678
# 노란색 에러는 수정 요구 사항
# 이건 어디서 수정 가능하냐? def __str__(self): 여기서!

class FibonacciShouldNotHaveNegativeNumberError(Exception):

    def __init__(self):
        pass

    def __str__(self):
        return "피보나치 수열은 index 값으로 양수를 받아야 합니다"

raise FibonacciShouldNotHaveNegativeNumberError()

def fibo(x):
    if x < 0:
        raise FibonacciShouldNotHaveNegativeNumberError(x)
    if x == 0:
        return 0
    if x == 1:
        return 1
    return fibo(x-1) + fibo(x-2)

class FibonacciShouldNotHaveNegativeNumberError(Exception):

    def __init__(self, n):
        self.n = n

    def __str__(self):
        return "이 함수는 index 값으로 양수를 받아야 합니다. (입력받은 값: {n})".format(n=self.n)   #에러메세지 요구사항

fibo(-13)


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
오류에는 2가지가 있다.
SyntaxError와 SyntaxError가 아닌 것(Exceptions)
Can you write Python code for it?

ab

def error(a, b):
    a = b + 1
    print(a)
error

2 + "김기표"

{}["somtthing"]

{}.append()

with open("./not_exist_file", "r") as f:
    pass


I am working on the file "Python 복습/05일차.화_디버깅,예외,예외처리,우분투,숙제_하노이의탑/5일차_디버깅,예외,예외처리,우분투.ipynb".
The first task is:
우리만의 예외처리 class를 만들어보겠다.
Can you write Python code for it?

def fibo(x):
    if x < 0:
#         err = FibonacciShouldNotHaveNegativeNumberError()
#         raise err
        #일반적으로 위와 같은 2줄이 아닌 아래와 같은 1줄로 적는다.

        raise FibonacciShouldNotHaveNegativeNumberError()

    if x == 0:
        return 0
    if x == 1:
        return 1
    return fibo(x-1) + fibo(x-2)

#Exception Class
class FibonacciShouldNotHaveNegativeNumberError(Exception):

    def __init__(self):
        pass


I am working on the file "Python 복습/07일차.목_크롤링, 정규표현식/7일차_1~3T_피보나치 class, 크롤링(naver).ipynb".
The first task is:
클래스의 역할은 관련 있는 값들과 관련 있는 행동(메쏘드)를 모아놓는 역할
관련 있는 값(속성) + 관련 있는 행동(함수, 메쏘드)
값이라는 것은 클래스가 가지고 있는 속성들
예를 들면 student의 경우에는 이름, 나이, 자기 소개 텍스트
행동은 함수(메쏘드)
Can you write Python code for it?

class Student():
    def __init__(self, name):
        self.name = "kipoy"

    def create_study_mate(self, other):   #self, other
        pass

# kipoy.create_study_mate(kimkipyo)
# kimkipyo = Student(...)


I am working on the file "Python 복습/07일차.목_크롤링, 정규표현식/7일차_5T_정규표현식.ipynb".
The first task is:
이 자체로 훌륭한 테스트 코드라고 말하는 것은 어렵다.
주피터 노트북용 테스트 코드였다.
python에서는 테스트 코드를 작성할 수 있는 unittest 모듈을 제공한다.
Can you write Python code for it?

# 우선 형태만 보면
# class TestDoubleFunction(unittest.TestCase):
#     def test_5_should_return_10(self):
#         self.assertEqual(double(5), 10)   # 이거랑 동일 assert double(5) == 10
# 주피터노트북에서는 이러한 형태로 테스트 못한다. 그래서 일단 pass

# 우선 hello.py라는 txt파일을 만든다. 안에 내용은
# def hello(name):
#     print("hello, {name}".format(name=name))

# hello("kimkipoy")
# hello("김기표")

%run hello.py


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_1T,3T_정규 표현식_이메일, 핸드폰 번호, Class_.ipynb".
The first task is:
3T_객체 지향 프로그래밍 - 클래스 메쏘드와 인스턴스 메쏘드

Class - 클래스는 매우 중요합니다.
Class => object ( 객체가 생성되는 클래스 ) 에 대해서만 배웠다.

예제: 피보나치 수열
Can you write Python code for it?

class Fibonacci():

    cache = {1: 0, 2: 1}
    # n=1 => 0
    # n=2 => 1
    # f(n) = f(n-1) + f(n-2)

#     def __init__(self):
#         self.cache = {}
# 기존의 이런 형태가 아니라 다른 형태로 받기 위해서

    # 클래스 => 클래스 메쏘드
    # 객체 ( 인스턴스 ) => 인스턴스 메쏘드

    @staticmethod  # 클래스 메쏘드
    def calc(n):  # self 가 없습니다. self.cache가 아니라 Fibonacci.cache로 바뀜

        if n in Fibonacci.cache:
            return Fibonacci.cache[n]

        if n <= 0:
            return 0

#         if n == 1:
#             Fibonacci.cache[n] = 0
#             return Fibonacci.cache[n]

#         if n == 2:
#             Fibonacci.cache[n] = 1
#             return Fibonacci.cache[n]

        Fibonacci.cache[n] = Fibonacci.calc(n-1) + Fibonacci.calc(n-2)
        return Fibonacci.cache[n]

Fibonacci.calc(20)

Fibonacci.cache


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_1T,3T_정규 표현식_이메일, 핸드폰 번호, Class_.ipynb".
The first task is:
예제: Factorial
Can you write Python code for it?

class Factorial():

    cache = {
        1: 1,
    }

    @staticmethod
    def run(n):

        if n in Factorial.cache:
            return Factorial.cache[n]

        Factorial.cache[n] = n * Factorial.run(n-1)
        return Factorial.cache[n]

    @staticmethod
    def prettify():
        print("\n".join([
            "{n}! == {result}".format(n=key, result=value)
            for key, value
            in Factorial.cache.items()
        ]))

Factorial.run(4)

Factorial.prettify()


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_1T,3T_정규 표현식_이메일, 핸드폰 번호, Class_.ipynb".
The first task is:
예제: 달력
Can you write Python code for it?

import functools

class Calendar():

    __days = {
        1: 31,
        2: 28,
        3: 31,
        4: 30,
        5: 31,
        6: 30,
        7: 31,
        8: 31,
        9: 30,
        10: 31,
        11: 30,
        12: 31,
    }

    @staticmethod
    def is_leap(year):
        return\
            year % 4 == 0\
            and not year % 100 == 0\
            or year % 400 == 0

    @staticmethod
    def days_in(year):
        days = Calendar.__days.copy()

        # days 라는 새로운 변수 => Calendar.__days 를 가리키고 있는 애
        # 우리가 의도한 바 : 기존의 애를 복사하는 것

        days[2] += int(Calendar.is_leap(year))  # True => 1,
                                                # False => 0
        return days

    @staticmethod
    def total_days_in(year):
        return functools.reduce(
            lambda x,y: x+y,
            Calendar.days_in(year).values(),
        )

    @staticmethod
    def total_days_until(year):
#         total_days = 0
#         for i in range(1900, year):
#             total_days += Calendar.total_days_in(i)
#         return total_days
        return functools.reduce(
            lambda x,y: x+y,
            [
                Calendar.total_days_in(i)
                for i
                in range(1900, year)
            ]
        )

    # 1년 1월 1일 부터 특정 년도 까지의 day 수 합계를 구하시오.
    # 예, 1년 1월 1일 부터 2년 1월 1일 => 365
    #     1년 1월 1일 부터 3년 1월 1일 => 365 * 2
    # 하는 이유: day 수 합계 % 7 ==> 요일 ( 1년 1월 1일이 월요일 입니다 )

Calendar.total_days_until(1905)

Calendar.days_in(2016)


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_5T_웹 프로그래밍 맛보기.ipynb".
The first task is:
python3 app.py로 실행하면
직방 데이터가 웹상에 뜬다.
Can you write Python code for it?

from flask import Flask, render_template
import requests

app = Flask(__name__)   #__name__ == "__main__"

@app.route("/")
def home():
    return "
hello world

This is home
"

@app.route("/rooms/<room_id>")
def room(room_id):
    response = requests.get("https://api.zigbang.com/v1/items?detail=true&item_ids=" + str(room_id))
    return response.text

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="8080")


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_5T_웹 프로그래밍 맛보기.ipynb".
The first task is:
그리고 나서 다시 python3.app.py
새로운 터미널을 띄우고 나서
curl localhost:5000
Can you write Python code for it?

# from flask import Flask

# app = Flask(__name__)   #__name__ == "__main__"

# @app.route("/")
# def home():
#     return "hello world"

# if __name__ == "__main__":
#     app.run(host="0.0.0.0", port="8080")


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_5T_웹 프로그래밍 맛보기.ipynb".
The first task is:
다시 python3 app.py로 실행해보면
웹상에서 기존 주소로는 hello world가 뜨고

뒤에 /rooms/123을 붙이면 123이 출력된다.

그리고 나서 pip3 install requests 로 설치 후에
Can you write Python code for it?

from flask import Flask
import requests

app = Flask(__name__)   #__name__ == "__main__"

@app.route("/")
def home():
    return "hello world"

@app.route("/rooms/<room_id>")
def room(room_id):
    response = requests.get("https://api.zigbang.com/v1/items?detail=true&item_ids=" + str(room_id))
    return response.text

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="8080")


I am working on the file "Python 복습/08일차.금_정규표현식, class, 크롤링, 숙제/8일차_5T_웹 프로그래밍 맛보기.ipynb".
The first task is:
우측 상단에 Preview에서 preview~application을 클릭 후 주소가 나온다.
그거를 복붙해서 띄우면 자기만의 페이지가 뜬다.
Can you write Python code for it?

from flask import Flask

app = Flask(__name__)   #__name__ == "__main__"

@app.route("/")
def home():
    return "hello world"

@app.route("/rooms/<room_id>")
def room(room_id):
    return room_id

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="8080")


I am working on the file "Python 복습/10일차.금_크롤링과 API이용/10일차_1T,2T_크롤링(중고나라,iFrame,javascript).ipynb".
The first task is:
https://opentutorials.org/course/1375/6843 여기 참조
이걸로도 확인은 가능하나 우리는 https(안전한 곳). 그래서 보안 클릭해서 바꾸고 보면 됨
API형태의 ajax를 보지만 많은 종류의 ajax가 있다.
ajax는 asynchronous javascript and xml. 비동기적으로 페이지가 변하지 않는 상태에서 우리가 자바스크립트로 리퀘스트를 보낸 다음에 xml이라는 파일 양식을 받아오는 방식
그런데 이제 최근에는 xml이라는 방식보다 웹에서는 json을 많이 쓰면서 사실상 우리는 json을 받아오는 것임. json은 html도 있고 text도 있다.
이런 게 ajax. 웹사이트가 바뀌지 않으면서 우리가 클릭을 했을 때 웹사이트 뒤에서 동작이 일어나고 결과가 바뀌는 일련의 과정을 우리가 ajax라고 부른다.

2T_데이터 크롤링 유형 (4) - 한국형 웹사이트 ( iFrame, javascript )
Can you write Python code for it?

#이번에는 각자 주피터 노트북으로. 왜냐하면 selenium으로 할 것임
# coding: utf-8
from selenium import webdriver

driver = webdriver.Firefox()

driver.get("http://cafe.naver.com/joonggonara")

# "맥북" 이라는 키워드로 검색 ( * ) => find_ele.., send_keys, click
# 검색 결과로 나오는 게시글 크롤링

# 1. 검색창 element
# 2. send_keys("맥북")
# 3. 검색 버튼 element
# 4. click()

search_form_element = driver.find_element_by_css_selector("#topLayerQueryInput")
search_form_element.send_keys("맥북")

# 할 수 있는 훨씬 쉬운 방법들이 있습니다. 이따 javascript 통해서 할 예정입니다.

search_button_element = driver.find_element_by_css_selector(".btn-search-green")
search_button_element.click()

post_elements = driver.find_elements_by_css_selector("td.board-list")

len(post_elements)

#실제로는 있는데, 0이라고 나옴. 눈으로는 보이는데
#왜 그러냐면 특이하게 동작함. 이중 구조. 이중 Frame 형태이기 때문
#네이버는 꽤 많은 IFrame을 쓰고 있음

iframe_element = driver.find_element_by_css_selector("#cafe_main")

driver.switch_to_frame(iframe_element)  # 내부적으로는 focus가 옮겨진거.

post_elements = driver.find_elements_by_css_selector("td.board-list")

len(post_elements)
#관공서 사이트가 대부분 이런 형태로 되어 있음

post_element = post_elements[0]

post_element

title = post_element.find_element_by_css_selector("a").text
url = post_element.find_element_by_css_selector("a").get_attribute("href")

print(title)
print(url)

for post_element in post_elements:
    title = post_element.find_element_by_css_selector("a").text
    url = post_element.find_element_by_css_selector("a").get_attribute("href")

    print(title)
    print(url)

# 정적인 ( HTML )
# 동적인 ( API; json, xml )
# 동적인 ( Selenium )
# + 한국형 웹사이트
#   - selenium iFrame
#   - selenium javascript

#http://kcia.or.kr/cid/Document/020.Ingredient_shis/INGREDIENT_SHIS_10L.asp
#화장품 성분명 사이트 실습.

driver = webdriver.Firefox()

driver.get("http://kcia.or.kr/cid/Document/020.Ingredient_shis/INGREDIENT_SHIS_10L.asp")

driver.execute_script('fGoPage(1)')

for page in range(1, 100+1):
    driver.execute_script("fGoPage({page})".format(page=page))

driver = webdriver.Firefox()

driver.get("http://fastcampus.co.kr")

driver.execute_script("alert('무료 수강권 이벤트에...


I am working on the file "Python 복습/10일차.금_크롤링과 API이용/10일차_1T,2T_크롤링(중고나라,iFrame,javascript).ipynb".
The first task is:
이미지 가져오기
Can you write Python code for it?

from IPython.display import Image

content_element = dom.select_one("#postContent")

image_elements = content_element.select("img")

len(image_elements)

image_elements[1].get('src')

image_url = image_elements[3].get('src')   #인덱스 바꾸면서 url 계속 입력하면서 확인
image_url

# image_url = "".join(image_url.split("?")[:-1])
print(image_url)
#iPython에서 이렇게 제거하면 할 수 있는 방법은 없다.

image_url

from IPython.display import IFrame

IFrame(image_url, width=300, height=200)


I am working on the file "Python 복습/11일차.목_Pandas/11일차_1T_Pandas 의 자료형 - Series, DataFrame.ipynb".
The first task is:
Numpy => 수학적인 연산; Number, Matrix ( C ) => Matlab ( low-level )
Pandas => 데이터 분석; ( Pandas를 설치하기 위해서 Numpy 가 필요합니다. ) ( high-level )(내부적으로 Numpy가 쓰여 계산이 된다.)

scipy => 수학계산; 과학적인 계산...

scikit-learn => 미리 머신러닝 알고리즘이 구현되어 있는 라이브러리

tensorflow => 미리 머신러닝/딥러닝 알고리즘이 구현되어 있는 라이브러리

scikit-learn, tensorflow 이 데이터를 => pandas ( 머신러닝 X; 데이터 분석 )

파이썬 배울 때 순서

Zen of Python ( PEP0020 )

PEP0008 ( Pythonic한 방법 )

자료형

Pandas 배울 때 순서 => Pandas스러운 방법으로 개발

Pandas 자료형 ( DF; DataFrame )

Series, 2. DataFrame
Can you write Python code for it?

# Matrix ( 2차원 행렬; Column x Row )
pd.DataFrame()

# List, = Row나 Column 그 자체
pd.Series()

animals = ["dog", "cat", "iguana"]
animals

len(animals)

animals_series = pd.Series(["dog", "cat", "iguana"])

animals_series

len(animals_series)


I am working on the file "Python 복습/11일차.목_Pandas/11일차_1T_Pandas 의 자료형 - Series, DataFrame.ipynb".
The first task is:
Pandas 에서 데이터 추가하기 ( 2 ) ( Series 로 하는거 말고, 우리가 직접 입력하는 경우 )
Can you write Python code for it?

df = pd.DataFrame(columns=["Name", "Email"])

df.loc[0] = ["김기표", "kkp@gmail.com"]   # 데이터 추가하기 (1)

df.loc[0]

df

# 이것을 정확히 쓰기 위해서는 Column의 정확한 "순서"를 알고 있어야 합니다.
df.loc[0] = ["kkp@gmail.com", '김기표']
df

#좋은 입력 방식. 딕셔너리 방식으로 넣으면 된다.
df.loc[1] = {"Name": "강기표", "Email": "kkp@naver.com"}
df

#데이터의 Row를 추가하는 방법에 대해서 다룸
#데이터 Column을 추가하려면?

df["Address"] = ""
df

# Address => "대기빌딩 지하2층 교무실 ____ 앞"
# 최대한 다양한 방법으로 해보시면 됩니다. ( 3가지+ )

# 1. for 문으로 시작하자. df.loc[____]

for i in range(len(df)):
    name = df.loc[i]["Name"]  #이름을 뽑았어요.
    df.loc[i]["Address"] = "대기빌딩 지하2층 교무실 " + name + " 앞"
    # + => 더하는 방법
    # %s => 문자열 치환
    # {name} => 문자열 치환 ( formatting )

df

# 2. for 문을 돌린다. ( 쉽게 돌리는 방식 )
# 제가 잘 몰랐어요. 없는 거고 이거 까먹으시면 됩니다.

for index, row in df.iteritems():
#     df.loc[index]["Address"] = "대기빌딩 지하2층 교무실 " + df.loc[index]["Name"] + " 앞"
    print(index)  #for문을 안 도는 이유는 index가 아니고 column이 나온다.
# df

df["Address"] = ""

df

df["Address"] = "대기빌딩 지하 2층 교무실 " + df["Name"] + " 앞"
df
#왜 되는지 모르겠다. 그냥 되는 거다.

df["Name"]   #Series가 뽑힌다. Series의 기능? 연산이 가능하다.

df["Name"] + " 앞"   #이렇게 Series로 자동 연산이 쭉 된다.

# 함수형 프로그래밍을 이용하자.
df["Address"] = ""
df

def get_address(name):
    return "대기빌딩 지하 2층 교무실 " + name + " 앞"

get_address("김기표")

df["Name"].apply(get_address)

df

df["Address"] = df["Name"].apply(lambda name: "대기빌딩 지하 2층 " + name + " 앞")

df