In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the coding skills with Python". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the coding skills with Python"?
1. The importance of readability
Programs must be written so that people can read them, and then machines can execute them.
First of all, follow the programming specification to make the program easy to read. Programming specifications are what experienced programmers follow when writing their code. Apart from ignoring these specifications, there is no other way to prove that you are a "novice" more quickly. Some of these specifications are specific to Python;, while others can be used by computer programmers in all languages.
In essence, readability is a feature that determines how easy it is for others to understand parts of your code (not you!).
For example, I was not used to writing code in vertical alignment, nor am I used to aligning function parameters with initial delimiters.
# No, to avoid: func = long_function_name (var_one, var_two, var_three, var_four) # Yes, func = long_function_name (var_one, var_two, var_three, var_four)
Check out the Python Code style Guide (other examples in https://www.python.org/dev/peps/pep-0008/)) and determine which one looks best.
Another important thing we often do is to emulate programs we have seen or written, which is why exposure to readable programs is so important for programming learning.
two。 Avoid useless conditions
Usually, a string of if & elif & … . & the else long condition is a sign that code needs to be refactored. These conditions make your code lengthy and very difficult to interpret. Sometimes this code can be easily replaced, for example, I have done this all the time:
Def f (): if condition: return True else: return False
This is stupid! This function returns a Boolean value, so why use if blocks in the first place? The right thing to do is:
Def f (): return condition
In a Hackerrank challenge, contestants need to write a function to determine whether a given year is a leap year. In the Gregorian calendar, three criteria must be considered to determine leap years:
The year is divisible by 4 and is a leap year unless:
The year is also divisible by 100, not a leap year, unless:
The year is also divisible by 400. It is a leap year
In this challenge, do not consider the ifs and elses conditions, just do the following:
Def is_leap (year): return year% 4 = = 0 and (year% 400 = = 0 or year% 100! = 0)
3. Appropriate use of whitespace
Do not confuse the keyboard tabulation positioning key with the space bar
Perform a line break between functions
Make two line breaks between levels
Enter a space after the "," of the argument in the library, list, tuple, and list of arguments, and enter a space after the ":" of the library.
Place spaces before and after allocation and comparison (except for arguments in the list)
There are no spaces before and after parentheses or before the parameter list
Def function (key, value=0): "Return a dictionary and a list..." D = {key: value} l = [key, value] return d, l
4. Documentation strings and comments
Document string = how to use the generation
Comment = why the code can (reasonably) execute and how to execute
The document string explains how to use the code:
Explain the purpose of the function, even if it is obvious to you. But in the future, its use may not be equally obvious to others.
Describe expected parameters, return values, and exceptions.
If this type of function is tightly coupled to a single Caller, mention the calling function.
These comments explain the maintenance requirements to the code maintainer. The following example also includes comments for yourself, such as:
#! BUG: …
#! FIX: This is a hack
#? Why is this here?
It is your responsibility to write well documented strings and comments, so always keep them up to date! When making changes, make sure that the comments and documentation strings are consistent with the code.
You will use the "document string convention"
(find a detailed PEP specifically for document strings in https://www.python.org/dev/peps/pep-0257/)
5. Variables and assignments
In other programming languages:
C = an a = b b = c
In Python, it is best to put the allocation item on a single line of code:
B, aa = a, b
You may have seen the code, but do you know how it executes?
A comma is the syntax that constructs a tuple.
Create a tuple (tuple package) on the right.
The tuple is the target on the left (tuple unpacking).
Other examples:
Result =''for s in colors: result + = s
Useful in structured data loops (the above variable names have been retained):
Result = '.join (colors)
You can also do the opposite by making sure that the left and right sides have the same structure:
> > jan, (gname, gtitle, gphone) = people > gname 'German' > gtitle' GBT' > gphone 'unlisted' > jan [' Jan', 'Gomez',' + 1,888,222-1546']
6. List splicing & merging
Start with the list of strings:
Colors = ['red',' blue', 'green',' yellow']
We want to concatenate these strings together to create a long chain. Especially when the number of substrings is large, avoid doing this:
Result =''for s in colors: result + = s
It's very slow to do this. And takes up a lot of memory and performance. The sum will accumulate, store, and then proceed with each intermediate step.
Instead, do the following:
Colors = ['red',' blue', 'green',' yellow'] print ('Choose',', '.join (colors [:-1]),\' or', colors [- 1]) > > Choose red, blue, green or yellow
The join () function makes an entire copy at once. When dealing with only a few strings, it is no different from other functions. But it can get you into the habit of building long chains with the best functions, because using the join () function does make a big difference when faced with hundreds of strings.
Here are some tips for using the join () function. If you want to use spaces as delimiters:
# Do this: # And not this: if x: if x = = True: pass pass# Do this: # And not this: if items: if len (items)! = 0: pass pass# and especially not that: if items! = []: pass
Or commas and spaces:
Result =', '.join (colors)
To make the sentence grammatically correct, use a comma between every value except the last value (people prefer to use "or"). The syntax for splitting the list will do the rest. [:-1] returns everything except the last value, which we can connect with a comma.
Colors = ['red',' blue', 'green',' yellow'] print ('Choose',', '.join (colors [:-1]),\' or', colors [- 1]) > > Choose red, blue, green or yellow
7. Test real conditions
In terms of Boolean values, using Python is simple and fast:
# Do this: # And not this: if x: if x = = True: pass pass# Do this: # And not this: if items: if len (items)! = 0: pass pass# and especially not that: if items! = []: pass
8. Use enumerated functions whenever possible
The enumeration function takes a list and returns pairs (exponents, items):
Items = ['zero',' one', 'two',' three'] > print list (enumerate (items)) [(0, 'zero'), (1,' one'), (2, 'two'), (3,' three')]
It is necessary to use lists to display results because enumerated functions are lazy functions that generate one item (pair) at a time only when required. This mechanism is required for for loops. The Print function will not get any results at once, but you must have the complete message to display. Therefore, we should automatically convert the generator to a list before using the Print function.
Therefore, it is better to use the following loop:
> [(x, y) for x in (1,2,3,4) if x% 2 = = 0 for y in ['await,' b'] if y = ='b'] [(2,'b'), (4,'b')]
The version that uses enumerated functions is shorter and simpler than the other two versions. The above is an example of an enumerated function returning an iterator (a generator is a kind of iterator).
9. List derivation
The traditional way to use for and if:
Let's sum the squares of numbers less than 100: # With a loop: total = 0 for num in range (1,101): total + = num * num
Use list derivation:
New_list = [fn (item) for item in a_list if condition (item)]
The list is clear and direct. You can include several for loops and if conditions in the same list derivation, but if there are more than two or three, or if the conditions are complex, I recommend that you use a normal for loop.
For example, a list of quadratic powers from 0 to 9:
> [n * * 2 for n in range (10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Odd list in the previous list:
> [n * * 2 for n in range (10) if n% 2] [1, 9, 25, 49, 81]
More examples:
> [(x, y) for x in (1,2,3,4) if x% 2 = = 0 for y in ['await,' b'] if y = ='b'] [(2,'b'), (4,'b')]
10. Generator expression
Let's sum the squares of numbers less than 100:
Let's sum the squares of numbers less than 100: # With a loop: total = 0 for num in range (1,101): total + = num * num
You can also use the sum function to get the work done faster for us by building the correct sequence.
# With a list comprehension: total = sum ([num * num for num in range (1101)]) # With a generator expression: total = sum (num * num for num in xrange (1101))
Generator expressions are similar to list deductions, except that they are lazy when evaluated. List deduction calculates the entire result at once, and then stores it in the list. If necessary, the generator expression evaluates one value at a time. Generator expressions are especially useful when the sequence is long and the resulting list is an intermediate step rather than the final result.
For example, if we had to sum the squares of billions of integers, using list derivation would reach memory saturation, but there would be no problem using generator expressions. Although it will take a while!
Total = sum (num * num for num in range (1, 1000000000))
The grammatical difference between the two is that the list derivation has square brackets, while the generator expression does not. Generator expressions sometimes require parentheses, so you should always use them.
In short:
Use list deduction when the expected result is a list.
Use a generator expression when the list is only an intermediate result.
At this point, I believe you have a deeper understanding of "what are the coding skills with Python?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.