Python

# Python Code Examples10 min read

Examples, FAQs (Frequently Asked Questions), notebooks and other little bits of code that we hope to be able to copy paste without understanding them. Sometimes it’s true.

## Classic Construction

### Calculation of a Sum

Calculation of a sum always involves a loop because the Python language can add only two numbers. The schema is always the same: initialization and loop.

Output:

This code is equivalent to the sum function. In this case where the sum integrates the result of a function (in the mathematical sense) and not the elements of a list, it would be necessary to write:

Output:

And these two lines could be summed up in one thanks to one of these instructions:

Output:

The advantage of the last two instructions is that they avoid the creation of an intermediate list, it is a point to take into account if the list on which operates the sum is voluminous.

### Calculating the sum of the first ten integers squared

This simple calculation can be written in different ways.

In short:

### Count

Here we want to count the number of occurrences of each element of an array. For example, one could know by this means the popularity of a word in a political speech or the extent of the vocabulary used. The following example counts the words in a word list.

Output:

The most appropriate structure here is a dictionary since one tries to associate a value with an element of a list that can be of any type. If the list contains editable elements like a list, these should be converted into an immutable type such as a string. The following example illustrates this case by counting the occurrences of the rows of a matrix.

Output:

One can also want not to count the number of occurrences but to memorize the positions of the elements all identical. One must use a dictionary of lists:

Output:

If you just have to count, the simplest writing is:

Output:

### Converting a vector into a matrix

In a language like C ++, it often happens that a matrix is not represented by a list of lists but by a single list because this representation is more efficient. It is therefore necessary to convert an index into two row and column indices. Of course, the number of columns on each line must be constant. The first program converts a list of lists into a single list.

Output:

Converting a string to a datetime

This is the kind of function that we do not use often but it is hard to find when we need it. You have to use the strftime function.

### Converting a string into a matrix

The next few lines allow you to break a string into a matrix. Each row and column are separated by different separators. This process often occurs when information is retrieved from a text file itself from a spreadsheet.

Output:

As this operation is very common when working with the data, it is no longer implements itself. It is preferred to use a module as pandas that is more robust and considers more cases. To write, use the to_csv method, to read, the function read_csv. You can also directly save in Excel read_excel format and write in the same format to_excel.

Output:

### Converting a matrix into a vector

In a language like C ++, it often happens that a matrix is not represented by a list of lists but by a single list because this representation is more efficient. It is therefore necessary to convert an index into two row and column indices. Of course, the number of columns on each line must be constant. The first program converts a list of lists into a single list.

Output:

You may also like: Python Tutorial with Exercises

You can also use functions such as reduce.

Output:

### Function as parameter

A function can also receive another function as parameter. The following example includes the function calculuevalue which takes as parameters l and f. This function calculates for all the values x in the list l the value f (x). function_carre or function_cube are passed in parameters to the function calculuevalue which executes them.

Output:

### Minimum with position

The min function returns the minimum of an array but not its position. The first reflex is then to recode the course of the list while maintaining the position of the minimum.

Output:

But there is a trick to get the position without having to reprogram it.

Output:

The min function chooses the minimum element of an array whose elements are couples (element of the first array, its position). The minimum is chosen by comparing the elements, and the position will disperse the equel.

### Search with index

When looking for an element in a table, one looks for its position more often than the fact that the array contains this element.

Output:

In python, there is a simple function that allows you to do that:

When the element is not there, we often return the position -1 which can not be taken by any element:

Even if this piece of code runs twice over the table (once determining its presence, a second time for its position), this code is often faster than the first version and the probability of making a smaller error.

Python 3 Examples

### two dimensional research

The two dimensional search is faster than a classical search but it assumes that it is done in a sorted set. The idea is to cut in half the search interval at each iteration. As the whole is sorted, by comparing the sought element to the central element, one can eliminate a part of the whole: the lower or upper half.

### Sort, keep the initial positions

Sorting is a frequent operation. We do not always have the time to program the most efficient sorting as a quicksort sort and a simpler sort is enough most of the time. The next sort is to find the smallest item and then swap its place with the first item in the table. We repeat the same procedure from the second position, then the third and so on until the end of the table.

Output:

The sorted function also sorts a list but uses a more efficient algorithm than this one (see Timsort). We sometimes have to reprogram a sort because we want to keep the position of the elements in the unsorted array. This happens when you want to sort an array and apply the same transformation to a second array. It is always best not to reprogram a sort (less error). Just apply the same idea as for the minindex function.

Output:

If this writing is too succinct, it can be broken down into:

Output:

## Negative Constructions

### Avoid making the same call twice

In this function we calculate the variance of a series of observations.

### Edit a dictionary by browsing it

You must avoid changing a container while traveling. When deleting an element from a dictionary, the structure of the dictionary is modified and affects the loop that traverses it. The loop always goes through the old dictionary structure, the one that existed at the beginning of the loop.

In Python, this produces the following error but other languages do not prevent (C ++) and this results in an error that occurs later in the code (such as an unexpected numeric value).

It is necessary to avoid that to store the elements which one wants to modify to remove them then.

Even if Python allows this for lists, it is advisable to abstain as well as for any type of objects that contains others. It’s a habit that will serve you for most other languages.

### 1 Comment

• […] More examples: Python Examples […]