2021年6月13日 星期日

[ Python 文章收集 ] How to Make Python Code Run Incredibly Fast

 Source From Here

Preface
Python is one of the most popular programming languages among developers. It is used everywhere, whether it’s web development or machine learning.

There are many reasons for its popularity, such as its community support, its amazing libraries, its wide usage in Machine Learning and Big Data, and its easy syntax.

Despite having these many qualities, python has one drawback, which is its slow speed. Being an interpreted language, python is slower than other programming languages. Still, we can overcome this problem using some tips.

In this article, I will share some python tricks using which we can make our python code run faster than usual. Let’s get started!

1. Proper algorithm & data structure
Each data structure has a significant effect on runtime. There are many built-in data structures such as list, tuple, set, and dictionary in python. Most of the people use list data structure in all the cases.

In python, sets and dictionaries have O(1) lookup performance as they use hash tables for that. You can use sets and dictionaries instead of lists in the following cases:
* You do not have duplicate items in the collection.
You need to search items repeatedly in the collection.
* The collection contains a large number of items.

You can see the time complexity of different data structures in python here: Time Complexity via Python Wiki
This page documents the time-complexity (aka "Big O" or "Big Oh") of various operations in current CPython...

2. Using built-in functions and libraries
Python’s built-in functions are one of the best ways to speed up your code. You must use built-in python functions whenever needed. These built-in functions are well tested and optimized.

The reason these built-in functions are fast is that python’s built-in functions, such as minmaxallmap, etc., are implemented in the C language.

You should use these built-in functions instead of writing manual functions that will help you execute your code faster. Let's check a simple example:
  1. newlist = []  
  2.   
  3. for word in wordlist:  
  4.     newlist.append(word.upper())  
A better way to write this code is:
  1. newlist = map(str.upper, wordlist)  
Here we are using the built-in map function, which is written in C. Therefore, it is much faster than using a loop.

3. Use multiple assignments
If you want to assign the values of multiple variables, then do not assign them line by line. Python has an elegant and better way to assign multiple variables.

Example:
  1. firstName = "John"  
  2. lastName = "Henry"  
  3. city = "Manchester"  
A better way to assign these variables is:
  1. firstName, lastName, city = "John""Henry""Manchester"  
This assignment of variables is much cleaner and elegant than the above one.

4. Prefer list comprehension over loops
List comprehension is an elegant and better way to create a new list based on the elements of an existing list in just a single line of code.

List comprehension is considered a more Pythonic way to create a new list than defining an empty list and adding elements to that empty list.

Another advantage of list comprehension is that it is faster than using the append method to add elements to a python list.

Example: Using list append method:
  1. newlist = []  
  2. for i in range(1100):  
  3.     if i % 2 == 0:  
  4.         newlist.append(i**2)  
A better way using list comprehension:
  1. newlist = [i**2 for i in range(1100if i%2==0]  
Code looks cleaner when using list comprehensions.

5. Proper import
You should avoid importing unnecessary modules and libraries until and unless you need them. You can specify the module name instead of importing the complete library.

Importing the unnecessary libraries will result in slowing down your code performance.

Example: Suppose you need to find out the square root of a number. Instead of this:
  1. import math  
  2. value = math.sqrt(50)  
Use this:
  1. from math import sqrt  
  2. value = sqrt(50)  
6. String Concatenation
In python, we concatenate strings using the ‘+’ operator. But another way to concatenate the strings in python is using the join method.

Join method is a more pythonic way to concatenate strings, and it is also faster than concatenating strings with the ‘+’ operator.

The reason why the join() method is faster is that the ‘+’ operator creates a new string and then copies the old string at each step, whereas the join method does not work that way.

Example:
  1. output = "Programming" + "is" + "fun  
Using join method:
  1. output = " ".join(["Programming" , "is""fun"])  
The output of both methods will be the same. The only difference is that the join() method is faster than the ‘+’ operator.

Conclusion
That’s all from this article. In this article, we have discussed some tricks that can be used to make your code run faster. These tips can be used especially with competitive programming where the time limit is everything. I hope you liked this article. Thanks for reading!

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...