Elegant Coding Style for Python

This serves as a note and a summary on my journey to become a coder who writes very elegant python code. Python is very different compared with most of other language; it is not like C/C++, which only has some basic key words support and takes a lot effort to import and integrate with other non-built in libraries. Python has large amount of built-in functions that can ease your coding life and tons of third party libraries which you can easily install with just pip install command and import them in one second. So, there is flexibility.

Currently, I am studying how to balance the amount of using built-in functions and third party libraries. Which one is better, and which one is more important? I would prefer to know both. But, anyway, this is not my final conclusion, going to learn more and come back to re-conclude.

  1. map, filter, reduce

Using filter to get rid of irrelevant character which can be used as a pre-processing or used in algorithms. As the name suggests filter extracts each element in the sequence for which the function returns True. The reduce function is a little less obvious in its intent. This function reduces a list to a single value by combining elements via a supplied function. The map function is the simplest one among Python built-ins used for functional programming.

Here is another use case for filter(): finding intersection of two lists:

The reduce is in the functools in Python 3.0. It is more complex. It accepts an iterator to process, but it’s not an iterator itself. It returns a single result:

At each step, reduce passes the current product or division, along with the next item from the list, to the passed-in lambda function. By default, the first item in the sequence initialized the starting value.

Let’s make our own version of reduce.

We can concatenate a list of strings to make a sentence. Using the Dijkstra’s famous quote on bug:

We can get the same result by using join :

We can also use operator to produce the same result:

The built-in reduce also allows an optional third argument placed before the items in the sequence to serve as a default result when the sequence is empty.

2. if else abbreviation

3. Use collections

Python is known for its powerful general purpose built-in data types like list, dict, tuple and set. But Python also has collection objects like Java and C++. These objects are developed on top of the general built-in containers with additional functionalities which can be used in special scenarios.

The objective of this article is to introduce python collection objects and explain them with appropriate code snippets. The collections library contains the collections objects, they are namedtuples (v2.6), deque (v2.4), ChainMap(v3.3), Counter(v2.7 ), OrderedDict(v2.7), defaultdict(v2.5) .

Counter

A Counter is a container that keeps track of how many times equivalent values are added. It can be used to implement the same algorithms for which bag or multiset data structures are commonly used in other languages.

An empty Counter can be constructed with no arguments and populated via the update() method.

Accessing Counts

Once a Counter is populated, its values can be retrieved using the dictionary API.

Counter does not raise KeyError for unknown items. If a value has not been seen in the input (as with e in this example), its count is 0.

The elements() method returns an iterator that produces all of the items known to the Counter.

The order of elements is not guaranteed, and items with counts less than zero are not included.

Use most_common() to produce a sequence of the n most frequently encountered input values and their respective counts.

This example counts the letters appearing in all of the words in the system dictionary to produce a frequency distribution, then prints the three most common letters. Leaving out the argument to most_common() produces a list of all the items, in order of frequency.

Arithmetic

Counter instances support arithmetic and set operations for aggregating results.

Each time a new Counter is produced through an operation, any items with zero or negative counts are discarded. The count for a is the same in c1 and c2, so subtraction leaves it at zero.

Basic list,set, mapping, dictionary,string

4. Set min or max value

Python set min or max’s initial value:

5. Pay close attention to the followings

Python Set; Python List; Python list copy: this is very important, especially if we need to copy a two dimensional list or even higher, use deepcopy() from copy module.

A solution to the described problems is to use the module “copy”. This module provides the method “copy”, which allows a complete copy of a arbitrary list, i.e. shallow and other lists.

The following script uses our example above and this method:

String

If we want to put string or tuple in set, it should be like this:

Reference

http://www.bogotobogo.com/python/python_fncs_map_filter_reduce.php

https://pymotw.com/2/collections/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store