Fifth day of Python cultivation

Source: Internet
Author: User

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 functionRecursion depth 998It is not recommended to modify the recursive depth, because if 998 is not resolved, then this function is not suitable for recursive writingExample:    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) +2Age (1)`
`Recursive solution binary Lookup algorithm:99*99 can  99*100-99  is 9900-99 = 9801This is an algorithm that belongs to humans.Computer algorithm is to calculate some more complex problems, the use of space, or timeA more advantageous approachSpace is saving memory. Time is faster to calculate execution timeFor example sort 500 million numbers to find the smallest with the largest, is generally quick sort, heap sort, bubble sortFind features using algorithms`
`Dichotomy: Find problems that can only be found for ordered sets of numbersL = [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 ModulesBuilt-in ModulesAfter the Python parser is installed, these modules are provided together and are typically usedExpansion modulesNeed to download the installed modules yourselfPyPI website:www.pypi.orgCustom ModulesSelf-written modules4 Built-in modules:One collections ModuleOrdereddictProvides a number of other data structures, such as an ordered dictionary ordereddictD = Collections. Ordereddict ()CounterCalculate the number of occurrences of a stringDefaultdictFrom collections Import DefaultdictL = [11,22,33,44,55,66,77,88]my_dict = defaultdict (list)The default value of this dictionary is an empty listPrint (my_dict["a"])My_dict["B"] = 10Print (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.NamedtupleCreate 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 nameDequeDouble-ended queue that can quickly append and eject objects from the other sideTwo time modulesDefinition: 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 timeDateTime is a module that is encapsulated again based on the time module.Three random modulesRandom decimalsRandom.random () decimals greater than 0 and less than 1Random.uniform (1,3) more than 1 decimals less than 3Practice:Send Red EnvelopesRandom integersRandom.randint (0,9) take one to twoPractice:Verification Codes = ""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 + = sPrint (ss)Randomly selects a returnRandomly select multiple returns, the number returned is the second parameter of the functionQuad OS ModuleSystem-related modulesFile operation:deleting filesOs.remove ()Renaming filesOs.rename ("old", "new")Directory Operations:Os.makedirs ("Dir1/dir2") multi-layered recursive creation of directoriesOs.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 onOs.mkdir ("Dir1") generates a single-level catalogOs.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 listCurrent 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 modeSt_ino inode Node NumberSt_dev Inode-Resident deviceSt_nlink inode Number of connectionsSt_uid Owner's User IDSt_gid owner's Group IDst_size normal files in bytes, containing data waiting for certain special filesSt_atime Last access timeSt_mtime Last modified metadata timeSt_ctime when the file content data was last modifiedOperating 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 \ nOS.PATHSEP output string to split the file path win; Linux:"Path1%spath2%s",%os.pathsepOs.name output string indicates the current use of platform, win is NT Linux is POSIXOperating system command execution:Os.system executes the command of the system, which is displayed directly.Os.system ("dir") executes the dir commandOs.popen executes the system command, returning the return value.ret = Os.popen ("dir"). Read ()Print (ret)Screen CuttingFive SYS modulePython parser moduleSys.exit () Interpreter exited, program endedSys.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 inIf sys.argv[1] = = "Alex" and sys.argv[2] = = "alex3714":Print ("Can execute the following code")ElsePrint ("Bad password Exit")Sys.exit ()This can only be executed from the command line and passed in parameters to useSix-RE Regular expression moduleFunctions, such as simple verificationA rule used when a regular expression string matches a related operationRules for regular expressionsUse the RE module in Python to manipulate regular expressionsOnline testing toolsHttp://tool.chinaz.com/regexRegular 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 characterMetacharacters. 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 tabsa\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 aa\$ match end here is match a for end characterThe capital is the opposite.\w is a match for non-numbers, letters, underscores[\w\w] This is a whole group that can match allabc| 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]QuantifiersThe {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 timesHow many times can a quantifier repeat a rule that constrains a character after a meta-characterIf 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 MGreedy withAll quantifiers in the regular expression will match you as much as possible.+ means match one or more timesAlgorithm: Back-up algorithmPractice: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 allret = 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 requiredret = Re.search ("\d+", "Df12 dsfs23dd Sdfs21")Print (Ret.group ())is generallyIF RET:Print (Ret.group ())Re.match on the search basis, adding a ^ match to each articleret = Re.match ("\d+", "Df12 dsfs23dd Sdfs21")Print (ret)The result is an emptyRe.split Matching CuttingRe.sub Replace the number with a string and specify the replacement several times afterret = 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 usedAttention:Priority of FindAllIf 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 regularTip: First count the parentheses inside theAnd then count the multiplication, and then add and subtract.Level three menu recursion or stackTime ModuleRed envelopes`

Fifth day of Python cultivation

Related Keywords:
Related Article

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.