Fifth day of Python cultivation

Source: Internet
Author: User
Tags month name python script

The fifth day, the feeling began to burn the brain. Recursive logic difficult, the number of modules, but the peerless martial arts are ten years to sharpen a sword out! Steady! 1 recursion.
Defining-----Recursion is calling itself inside a function
Recursion depth 998
It is not recommended to modify the recursive depth, because if 998 is not resolved, then this function is not suitable for recursive writing
Example:
Guess age
Alex is big, Alex is two years older than Wusir 40+2+2
Wusit, Wusir two years older than the boss 40+2
How old is Kim's boss, 40?
def age (N)
if n = = 3:
Return 40
Else
Return age (N+1) +2
Age (1)

Recursive solution binary Lookup algorithm:
99*99 can 99*100-99 is 9900-99 = 9801
This is an algorithm that belongs to humans.
Computer algorithm is to calculate some more complex problems, the use of space, or time
A more advantageous approach
Space is saving memory. Time is faster to calculate execution time

For example sort 500 million numbers to find the smallest with the largest, is generally quick sort, heap sort, bubble sort
Find features using algorithms

Dichotomy: Find problems that can only be found for ordered sets of numbers
L = [2,3,4,5,6,7,8,9,0,11,22,23,24,27,33,37,44,46,55,59,66,67,77,74,88,90,92,98]
def cal (num=66):
Length-len (L)
MID = Length//2
If num > L[mid]:
L = L[mid:]

def cal (L,num,start,end)
If Start < = end
Mid = (End-start)//2 +start
If L[MID] > num:
Return Cal (L,num,start,mid-1)
Elif L[mid] < num:
Return Cal (L,num,mid+1,end)
Else
Print ("Found", Mid,l[mid])
Else
Return "not Found"
2 Common Module 1 module definition: The module is the py file, the module is written well but not directly use the function.
2 Meaning of the module (excerpt):
If you quit the Python interpreter and then re-enter, then the functions or variables you defined previously will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.
With the development of the program, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. In this case, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the reuse of functionality,

3 Classification of modules:
Commonly used in relation to an operation is divided into three categories based on relevance: built-in modules. Extension module. Custom Modules
Built-in Modules
After the Python parser is installed, these modules are provided together and are typically used
Expansion modules
Need to download the installed modules yourself
PyPI website:
www.pypi.org
Custom Modules
Self-written modules

4 Built-in modules:
One collections Module
Ordereddict
Provides a number of other data structures, such as an ordered dictionary ordereddict
D = Collections. Ordereddict ()

Counter
Calculate the number of occurrences of a string

Defaultdict
From collections Import Defaultdict
L = [11,22,33,44,55,66,77,88]
my_dict = defaultdict (list)
The default value of this dictionary is an empty list
Print (my_dict["a"])
My_dict["B"] = 10
Print (my_dict)
If you create a new key and specify a value, then you assign a value to the value you specify, which is not the default list.

Namedtuple
Create a meta-ancestor, but the elements inside are represented by a name.
Generate a tuple that can access the content of an element by using a name

Deque
Double-ended queue that can quickly append and eject objects from the other side


Two time modules
Definition: Time modules typically have three ways to represent time: timestamps, formatted time strings, tuples (struct_time)
        1. Timestamp time: Represents the offset that is calculated in seconds from 00:00:00 on January 1, 1970
Print (Time.time ())

2. Format time:
Time.strftime ("%y-%m-%d%h:%m:%s")
There are also commonly used formats such as%x%c.
Format time string (excerpt):
%y Two-digit year representation (00-99)%y four-digit year (000-9999)%m month (01-12) one day (0-31)%H 24-hour hours (0-23) %I 12-hour hours (01-12)%M minutes (00=59)%s seconds (00-59)%a Local simplified week name%a Local full week name%b locally simplified month name%        B Local Full month name%c local corresponding date representation and time represents%j year of the Day (001-366)%p local a.m. or p.m. the equivalent of the number of weeks in the year (00-53) Sunday is the beginning of the week        %w Week (0-6), Sunday for the beginning of the week%w Week of the Year (00-53) Monday is the beginning of the week%x local corresponding date indicates%x local corresponding time represents%Z the name of the current time zone Percent% of the number itself
        3. Tuple time (struct_time): Struct_time tuple total of 9 elements total nine elements: (year, month, day, hour, minute, second, week of the year, Day of the year, etc.)
Print (Time.localtime ())
t = Time.localtime ()
Format (excerpt)
indexing (Index) Properties (Attribute) value (values)
0 Tm_year (year) Like 2011.
1 Tm_mon (month) 1-12
2 Tm_mday (Sun) 1-31
3 Tm_hour (Time) 0-23
4 Tm_min (min) 0-59
5 Tm_sec (SEC) 0-60
6 Tm_wday (Weekday) 0-6 (0 = Monday)
7 Tm_yday (day ordinal of the year) 1-366
8 TM_ISDST (whether it is daylight saving time) Default is 0



4. Conversion of Time:
Can receive a timestamp time into localized time
Print (Time.localtime (1550000000))
Format time-to-string time
Stryct_time = Time_gmtime (20000000000)
Print (Time.strftime ("%y-%m-%d%h:%m:%s", Stryct_time))
Format time-to-timestamp time
s = "1988-12-22 9:23:22"
ret = Time.strptime (S, "%y-%m-%d%h:%m:%s", Stryct_time ")
Print (ret)
Print (Time.rmktime (ret))
    

        
Exercises:
1 Get the timestamp time of the 0 point at the beginning of the current time at the beginning of 1th.
2 Calculate the number of days and seconds between any two points of time
DateTime is a module that is encapsulated again based on the time module.

Three random modules
Random decimals
Random.random () decimals greater than 0 and less than 1
Random.uniform (1,3) more than 1 decimals less than 3
Practice:
Send Red Envelopes

Random integers
Random.randint (0,9) take one to two
Practice:
Verification Code
s = ""
For I in range (4):
s + = Rangom.randint (0,9)
Print (s)
Both letters and numbers are:
id = ""
num = Random.randint (65,90)
c = chr (num)
num2 = Random.randint (0,9)
Print (NUM2)
s = Random.choice ([c,num2])
Print (s)
For I in range (4):
ID + = s
Print (ss)
Randomly selects a return
Randomly select multiple returns, the number returned is the second parameter of the function


Quad OS Module
System-related modules
File operation:
deleting files
Os.remove ()
Renaming files
Os.rename ("old", "new")
Directory Operations:
Os.makedirs ("Dir1/dir2") multi-layered recursive creation of directories
Os.removedirs ("Dir1") if the directory is empty, it is deleted and recursively to the previous level directory. If it is also empty, it is deleted. And so on
Os.mkdir ("Dir1") generates a single-level catalog
Os.rmdir ("Dir1") Delete the single-level empty directory directory is not empty and cannot be deleted.
Os.listdir ("Dir1") lists all files and subdirectories under the specified directory. Include hidden files and print as a list
Current working directory about actions:
OS.GETCWD () Gets the current working directory. The directory path where the current Python script works.
Os.chdir ("Dir1") changes the current script working directory. As opposed to the shell CD, note that if you change the path of the open file, the file is created under the changed path.
Os.curdir () returns the current directory: "."
Os.pardir () put back the top level directory: "..."
Stat Property Operation:
Os.stat ("Dir/file")
St_mode inode Protection mode
St_ino inode Node Number
St_dev Inode-Resident device
St_nlink inode Number of connections
St_uid Owner's User ID
St_gid owner's Group ID
st_size normal files in bytes, containing data waiting for certain special files
St_atime Last access time
St_mtime Last modified metadata time
St_ctime when the file content data was last modified
Operating System differences:
OS.SEP output operation system-specific path delimiter win is \ \ linux/
OS.LINESEP output The line terminator used by the current platform win is \t\n Linux is \ n
OS.PATHSEP output string to split the file path win; Linux:
"Path1%spath2%s",%os.pathsep
Os.name output string indicates the current use of platform, win is NT Linux is POSIX
Operating system command execution:
Os.system executes the command of the system, which is displayed directly.
Os.system ("dir") executes the dir command
Os.popen executes the system command, returning the return value.
ret = Os.popen ("dir"). Read ()
Print (ret)
Screen Cutting


Five SYS module
Python parser module
Sys.exit () Interpreter exited, program ended
Sys.modules #放了所有在解释器运行过程中导入的模块名称.
Sys.path the path associated with the program. Whether a module can be imported needs to see if there is a path underneath the Sys.path list.
SYS.ARGV when executing a python script, you can pass some parameters in
If sys.argv[1] = = "Alex" and sys.argv[2] = = "alex3714":
Print ("Can execute the following code")
Else
Print ("Bad password Exit")
Sys.exit ()
This can only be executed from the command line and passed in parameters to use

Six-RE Regular expression module
Functions, such as simple verification
A rule used when a regular expression string matches a related operation
Rules for regular expressions
Use the RE module in Python to manipulate regular expressions
Online testing tools
Http://tool.chinaz.com/regex

Regular Expressions:
[] Match characters at one character position
[0-9] Match 0 to 9 characters
[A-z] matches letters A through Z
[A-za-z] matches uppercase and lowercase letters
[0-9a-fa-f] matches a hexadecimal character

Metacharacters
. Match any one character
\d Match any number
\w matches any number, letter, underline
\s matches any one whitespace character
\ nthe match line break
\ t matches tabs
a\b matches the end of the word, here is whether the end is a
^a Match first here is a character that matches the beginning of a
a$ match end here is match a for end character

The capital is the opposite.
\w is a match for non-numbers, letters, underscores
[\w\w] This is a whole group that can match all

abc| ABCD if the two regular expressions match first to ABC then the match will not be matched, so write the long one to the front first.
should be written as abcd| Abc

[^...] If you add ^ in a character group, that's all except the character set. [^ABC]

Quantifiers
The {num} constraint occurs several times, only the preceding
[1] [3-9] [0-9] {9} is capable of matching the preceding [0-9] character Group 9 times
How many times can a quantifier repeat a rule that constrains a character after a meta-character
If the character you want to match is exactly the same as the meta character, you need to escape the metacharacters.

* Repeat 0 or more times
+ Repeat one or more times
? Repeat 0 or one time
{n} matches n times
{n,} repeats n or more times
{n,m} repeats n times to M


Greedy with
All quantifiers in the regular expression will match you as much as possible.
+ means match one or more times
Algorithm: Back-up algorithm
Practice:
Match integers to decimals
\d+ (/.\d+)?

Lazy Matching
? If after the quantifier, the number is an inert match.
\d+?
\d{3,5}? Matches only 3 times
?? Match only 0 or one time as few matches as possible
{N,}? Match n or more times and try to configure only n times
. *?x matches any character and stops when it touches an X.

Match ID
^[1-9]\D{14} (\d{2}[0-9x])? $

Re Module method:
Re.findall () matches all eligible values and returns all
ret = Re.findall ("\d+", "Df12 dsfs23dd Sdfs21")
Print (ret)

Re.search () Find the first one that meets the criteria. The value returned at the same time is a memory address. A group () call is required
ret = Re.search ("\d+", "Df12 dsfs23dd Sdfs21")
Print (Ret.group ())
is generally
IF RET:
Print (Ret.group ())

Re.match on the search basis, adding a ^ match to each article
ret = Re.match ("\d+", "Df12 dsfs23dd Sdfs21")
Print (ret)
The result is an empty

Re.split Matching Cutting


Re.sub Replace the number with a string and specify the replacement several times after
ret = re.sub ("\d", "G", "Adfasdf2131sdfsdf", 1)

RE.SUBN bar number is replaced with a string and returns Ganso (replacement result, number of times replaced)

Re.cap not used

Attention:
Priority of FindAll
If there is a grouping in the match, then only the matching of the grouping is returned, so the group priority needs to be removed before the group is added.:

Homework:
String calculator, subtraction parentheses, using regular
Tip: First count the parentheses inside the
And then count the multiplication, and then add and subtract.

Level three menu recursion or stack
Time Module
Red envelopes

Fifth day of Python cultivation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.