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.
Simulación de sentencia «switch (case)» en Python | DaW - Labs
La sentencia «switch (case)» es una estructura de control que permite controlar el flujo del programa basado en el valor de una variable o expresión. Se usa comúnmente para evitar el uso de if’s anidados, lo que en cierta parte disminuye la legibilidad y rapidez de un programa. Su funcionamiento es sencillo, si la variable o expresión tiene un número determinado de valores, se podría ejecutar una serie de acciones dependiendo de cada valor por separado. Un ejemplo en C y Pascal: Basándose en el valor de la variable Num (Integer) mostrará un mensaje de salida diferente. La mayoría de los lenguajes de programación cuentan con ésta sentencia, pero por desgracia Python no, en lugar de ello se usa una serie de bloques if-elif-else. Aquí un ejemplo como los anteriormente vistos: ¡Bien! Aquí está parte del código anterior usando ésta simulación: Con el uso de diccionarios en Python podemos hacer una sentencia bastante limpia y dejar de recurrir a excesivos if’s anidados.
First-class function
Concepts[edit] Higher-order functions: passing functions as arguments[edit] map :: (a -> b) -> [a] -> [b]map f [] = []map f (x:xs) = f x : map f xs void map(int (*f)(int), int x[], size_t n) { for (int i = 0; i < n; i++) x[i] = f(x[i]);} Anonymous and nested functions[edit] In languages supporting anonymous functions, we can pass such a function as an argument to a higher-order function: main = map (\x -> 3 * x + 1) [1, 2, 3, 4, 5] In a language which does not support anonymous functions, we have to bind it to a name instead: int f(int x) { return 3 * x + 1;} int main() { int list[] = {1, 2, 3, 4, 5}; map(f, list, 5);} Non-local variables and closures[edit] Once we have anonymous or nested functions, it becomes natural for them to refer to variables outside of their body (called non-local variables): main = let a = 3 b = 1 in map (\x -> a * x + b) [1, 2, 3, 4, 5] Also note that the map is now specialized to functions referring to two ints outside of their environment. Equality of functions[edit]
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
Python - Basic Operators
Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operator Python language supports the following types of operators. Arithmetic OperatorsComparison (Relational) OperatorsAssignment OperatorsLogical OperatorsBitwise OperatorsMembership OperatorsIdentity Operators Let us have a look on all operators one by one. Python Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. [ Show Example ] Python Assignment Operators [ Show Example ] Python Bitwise Operators Bitwise operator works on bits and performs bit by bit operation. a = 0011 1100 b = 0000 1101 a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Python language [ Show Example ] Python Logical Operators
Planet JavaScript
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).
alsaaudio — alsaaudio v0.7 documentation
Platforms: Linux The alsaaudio module defines functions and classes for using ALSA. alsaaudio.cards() List the available cards by name (suitable for PCM objects). alsaaudio.mixers([cardindex]) List the available mixers. class alsaaudio.PCM(type=PCM_PLAYBACK, mode=PCM_NORMAL, card='default') This class is used to represent a PCM device (both for playback and recording - capture). type - can be either PCM_CAPTURE or PCM_PLAYBACK (default).mode - can be either PCM_NONBLOCK, or PCM_NORMAL (default).card - specifies the name of the card that should be used. class alsaaudio.Mixer(control='Master', id=0, cardindex=0) This class is used to access a specific ALSA mixer. control - Name of the chosen mixed (default is ‘Master’).id - id of mixer – More explanation needed herecardindex specifies which card should be used. exception alsaaudio.ALSAAudioError Exception raised when an operation fails for a ALSA specific reason. PCM Objects class alsaaudio.PCM(type=PCM_CAPTURE, mode=PCM_NORMAL, card='default') or: