background preloader

HowTo/Sorting

HowTo/Sorting
Original version by Andrew Dalke with a major update by Raymond Hettinger Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here. Sorting Basics A simple ascending sort is very easy -- just call the sorted() function. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] You can also use the list.sort() method of a list. >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] Another difference is that the list.sort() method is only defined for lists. Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons. For example, here's a case-insensitive string comparison: The same technique works for objects with named attributes. Related:  PythonPython 2

PEP 257 -- Docstring Conventions What is a Docstring? A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory. String literals occurring elsewhere in Python code may also act as documentation. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".String literals occurring immediately after another docstring are called "additional docstrings". Please see PEP 258, "Docutils Design Specification" , for a detailed description of attribute and additional docstrings. Multi-line Docstrings

Pythonic Perambulations Python filter() In simple words, filter() method filters the given iterable with the help of a function that tests each element in the iterable to be true or not. The syntax of filter() method is: filter(function, iterable) filter() Parameters filter() method takes two parameters: function - function that tests if elements of an iterable return true or false If None, the function defaults to Identity function - which returns false if any elements are false iterable - iterable which is to be filtered, could be sets, lists, tuples, or containers of any iterators Return value from filter() filter() method returns an iterator that passed the function check for each element in the iterable. filter() method is equivalent to: # when function is defined (element for element in iterable if function(element)) # when function is None (element for element in iterable if element) Example 1: How filter() works for iterable list? Output The filtered vowels are: a e i o The filtered elements are: 1 a True 0

guaranteed-stable sort with the decorate-sort-undecorate idiom ( "decorate-sort-undecorate" is a general and common idiom that allows very flexible and speedy sorting of Python sequences. An auxiliary list is first built (the 'decorate' step) where each item is made up of all sort-keys (in descending order of significance) of the corresponding item of the input sequence (must include all of the information in the whole corresponding item, and/or an index to it so we can fetch it back [or reconstruct it] in the third step). This is then sorted by its builtin sort method without arguments. This 'naturally' supplies a sorted _copy_, but if the input-sequence is a list we can just assign to its "include everything" slice to get in-place effect. This recipe specifically demonstrates using this to achieve a stable sort (where items that compare equal keep the same relative order in the result list as they had in the input sequence).

Debugging Python Code on the Raspberry Pi with Wing IDE - Wingware Python IDE May 06, 2015 Wing IDE is an integrated development environment that can be used to develop and debug Python code running on the Raspberry Pi. Wing provides auto-completion, call tips, a powerful debugger, and many other features that help you write, navigate, and understand Python code. Introduction The Raspberry Pi is not really capable of running Wing IDE itself, but you can set up Wing IDE on a computer connected to the Raspberry Pi to work on and debug Python code remotely. To do this, you will first need (1) a network connection between the Raspberry Pi and the computer where Wing IDE will be running, and (2) a way to share files between the two computers. The easiest way to connect the Raspberry Pi to your network is with ethernet, or see the instructions at the end of Using Wing IDE with Raspberry Pi for configuring a wifi connection. For file sharing, use Samba, or simply transfer a copy of your files to the Raspberry Pi using scp or rsync. Installing and Configuring the Debugger

Iterate over a list in Python - GeeksforGeeks View Discussion Improve Article Save Article Like Article List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size. There are multiple ways to iterate over a list in Python. Method #1: Using For loop Python3 Output: Method #2: For loop and range()In case we want to use the traditional for loop which iterates from number x to number y. Iterating using the index is not recommended if we can iterate over the elements (as done in Method #1). Method #4: Using list comprehension (Possibly the most concrete way). Method #5: Using enumerate()If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search you might need to save the index of minimum element), you can use the enumerate() function. Note: Even method #2 can be used to find the index, but method #1 can’t (Unless an extra variable is incremented every iteration) and method #5 gives a concise representation of this indexing.

Python: Lambda Functions Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce(). This piece of code shows the difference between a normal function definition ("f") and a lambda function ("g"): As you can see, f() and g() do exactly the same and can be used in the same ways. The following code fragments demonstrate the use of lambda functions. The above code defines a function "make_inrementor" that creates an anonymous function on the fly and returns it. You can now create multiple different incrementor functions and assign them to variables, then use them independent from each other. The following takes this a step further. In the second example, map() is used to convert our list.

What is the python3 equivalent of "python -m SimpleHTTPServer" Python enumerate() The syntax of enumerate() is: enumerate(iterable, start=0) enumerate() Parameters enumerate() method takes two parameters: iterable - a sequence, an iterator, or objects that supports iteration start (optional) - enumerate() starts counting from this number. Return Value from enumerate() enumerate() method adds counter to an iterable and returns it. You can convert enumerate objects to list and tuple using list() and tuple() method respectively. Example 1: How enumerate() works in Python? grocery = ['bread', 'milk', 'butter'] enumerateGrocery = enumerate(grocery) print(type(enumerateGrocery)) # converting to list print(list(enumerateGrocery)) # changing the default counter enumerateGrocery = enumerate(grocery, 10) print(list(enumerateGrocery)) Output <class 'enumerate'> [(0, 'bread'), (1, 'milk'), (2, 'butter')] [(10, 'bread'), (11, 'milk'), (12, 'butter')] Example 2: Looping Over an Enumerate object

The Python Tutorial — Python v2.6.4 documentation Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python web site, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation. The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). This tutorial introduces the reader informally to the basic concepts and features of the Python language and system.

Removing An Axis Or Both Axes From A Matplotlib Plot Sometimes, the frame around a matplotlib plot can detract from the information you are trying to convey. How do you remove the frame, ticks, or axes from a matplotlib plot? matplotlib plot without a y axis The full example is available on github. First, we construct a figure and an axes object: The Axes object is a container that holds the axes, the ticks, the labels, the plot, the legend, etc. We’ll disable the drawing of ticks at the top of the plot: Now, we’ll turn off the y axis: Replace get_yaxis with get_xaxis to access the x axis. First, we obtain the limits of the current view. An alternate approach is to use the AxesGrid Toolkit, which comes with versions of Matplotlib 0.99 or higher.

Graphics Using Python Software - Maker Campus What You'll Do: Learn to use Python software to make simple graphics! Python is a programming language that is used extensively in industry and is really quite simple and fun! In this session we will learn how to use Python’s turtle program to create and animate shapes and to build some fun graphics. Prior experience is not necessary – as a matter of fact, we teach this class to children as young as 6 Please download the free Python version of Python from Python’s website (scroll down to find the file that aligns with your operating system) What You'll Need: Device with Python (free software) loaded Download the free Python version of Python from Python's website (scroll down to find the file that aligns with your operating system) About the Facilitator: After School Brilliance is a STEM-focused after school and day camp enrichment program.

Pyline: a grep-like, sed-like command-line tool. « ActiveState C Save the script as 'pyline' somewhere on your path, e.g. /usr/local/bin/pyline, and make it executable (e.g. chmod +x /usr/local/bin/pyline). When working at the command line, it's very useful to pipe multiple commands together. Common tools used in pipes include 'head' (show the top lines of a file), 'tail' (show the bottom lines), 'grep' (search the text for a pattern), 'sed' (reformat the text), etc. However, Python is found lacking in this regard, because it's hard to write the kind of one-liner that works well in an ad-hoc pipe statement. Pyline tries to solve this problem. Here are a couple examples: Print out the first 20 characters of every line in the tail of my Apache access log: tail access_log | pyline "line[:20]" Print just the URLs in the access log (the seventh "word" in the line): tail access_log | pyline "words[6]" Here's a tricker one, showing how to do an import. ls | pyline -m os "os.path.isfile(line) and os.stat(line).st_size > 1024 and line" Hopefully you get the idea.

Related: