[Python]Python and Algorithms

  1. The size of Python’s integers is limited only by the machine memory, not by a fixed number of bytes.
  2. The bin(i) method returns the binary representation of int i as a string.
  3. The hex(i) method returns teh hexadecimal representation of i as a string.
  4. The oct(i) method returns the octal representation of i as a string.
  5. Python represents strings, a sequence of characters, using the immutable str type.
  6. The splitlines(f) Method returns the list of lines produced by splitting the string on line terminators, stripping the terminators unless f is True.
  7. The split(t, n) method returns a list of strings splitting at most n times on string t. If n is not given, it splits as many as possible. If t is not given, it splits on whitespace.
  8. A tuple is an immutable sequene type consisting of values separated by commas.
  9. The append(x) method adds a new element at the end of the list. It is equivalent to list[len(list):] = [x].
  10. The insert(i, x) method inserts an item at a given position i: the first argument is the index of the element before which to insert.
  11. The pop() method removes the item at the given position in the list, and then returns it. If no index is specified, pop() returns the last() item in the list.
  12. Verify whether a number is a power of 2 by checking whether x&(x-1) is 0(if x is not an even power of 2, the highest position of x with a 1 will also have a 1 in x-1, otherwise, x will be 100…0 and x-1 will be 011…1; add them together they will return 0).
  13. In Python, a Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Sets are used for membership testing and eliminating duplicate entries. Sets have O(1) insertion.
  14. The discard(x) removes the item x from the set. remove(x) removes the item x from the set or raises a KeyErro exception if the element is not in the set. pop() returns and removes a random item from the set or raises a KeyError exception if the set is empty.
  15. Dictionaries in Python are implemented using hash tables.
  16. Accessing dictionaries has runtime O(1) so they are used to keep counts of unique items and for fast membership test.
  17. The setdefault() method is used when we want to access a key in the dictionary without being sure that this key exists(if we simply try to access a non-existent key in a dictionary, we will get an exception). With setdefault(), if key is in the dictionary, we get the value to it. If not, we successfully insert the new key with the value of default.
  18. The update([other]) method updates the dictionary with the key/value pairs from other, overwriting existing keys.
  19. If we do not define a return value, Python automatically returns None.
  20. The difference between yield and return is that the former returns each value to the caller and then only returns to the caller when all values to return have been exhausedm and the latter causes the method to exit and return control to the caller.
  21. Generators are like regular functions but instead of returning a final value in the end, they use the yield statement to return data during execution. In other words, values are extracted from the iterator one at time by calling its next() method and at each of these calls, the yield expression’s value is returned. This happens until the final call, when a StopIteration is raised.
  22. The enumerate() function returns a tuple with the item and the index value from an iterable.
  23. The zip function takes two or more sequences and creates a new sequence of tuples where each tuple contains one element from each list.
  24. The filter(function, sequence) function returns a sequence of those items from the sequence for which function(item) is true.
  25. The map(function, list) Function, a convenient way of turning a pair of lists into a list of pairs. It applies a function to every item of an iterable and then returns a list of the results.
  26. The read(size) method reads some quantity from the data and returns it as a string. Size is an optional numeric argument, when it is omitted or negative, the entire contents of the file will be read and returned. If the end of the file has been reached, read() will return an empty string.
  27. The readlines() method return a list containing all the lines of data in the file. If given an optional parameter size, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will ne returned.
  28. The write() method writes the contents of a string to the file, returning None. Write bytes/bytearray object to the file if opened in binary mode or a string object if opened in text mode.
  29. Each program in the operational system is a separate process. Each process has one or more threads.
  30. Each Python program has at least one thread, the main thread.
  31. When an exception is raised and not handled, Python outputs a traceback along with the exception’s error message. A traceback is a list of all the calls made from the point where the unhandled exception occurred back to the top of the call stack.
  32. Prefer tuples to list with read-only data
  33. use generators rather than large lists or tuples to iteration
  34. When creating large strings out of small strings, instead of concatenating the small, accumulate them all in a list and join the list of strings in the end.
    35.A namespace is a mapping from names to objects.
  35. A scope is a textual region of a Python program where a namespace is directly accessible.
  36. The decorator pattern allows us to wrap an object that provides core functionality with other objects that alter that functionality.
  37. A class follows the singleton pattern if it allows exactly one instance of a certain object to exist. Since Python does not have primate constructors, we use the new class method to ensure that only one instance is ever created. When we override it, we first check whether our singleton instance was created. If not, we create it using a super class call.
  38. A Stack is a linear data structure that can be accessed only at once of its end (which we will refers as the top) for either storing or retrieving.
  39. A queue is a structure where the first enqueued element (at the back) will be the first one to be dequeued (when it is at the front).
  40. A deque is a double-ended queue, which can roughly be seen as a union of a stack and a queue.
  41. A priority queue is an abstract data type which is similiar to a regular queue or stack, but where each element has a priority associated with it. If two elements have the same priority, they are served accordig to their order in the queue.
  42. A heap is a binary tree where each node is smaller (larger) than its children. When modifications are made in a balanced tree, we can repair its structure with O(logn) runtimes. min-(max-)heap will let you to find the smallest (largest) element in O(1) and to extract/add/replace it in O(ln n).
  43. Once we have a heap, the heapq.heappush(heap, push) method is used to push the item onto it.
  44. The method heapq.heappop(heap) is used to pop and return the smallest item from the heap.
  45. A linked list is simply a linear list of nodes containing a value and a pointer (a reference) to the next node (except for the last), where teh reference points to None.
  46. The simplest way of sorting a group of items is to start by removing the smallest item from the group, and putting it first. Then removing the next smallest, and putting it next and so on.
  47. Insertion sort is a simple sorting algorithm with best runtime case runtime of O(n) and average and woest runtime cases of O(pow(n, 2)). It sorts by repeatedly inserting the next unsorted element in an initial sorted segment of the array. For small data sets, it can be preferabe to more advanced algorithms such as merge sort of quicksort if the list is already sorted.
  48. Selection sort is based on finding the smallest or largest element in a list and exchanging it to the first, then finding the second, etc, until the end is reached.
  49. Gnome sort works by moving forward to find a misplaced value and then moving backward to place it in the right position.
  50. Count sort sorts integers with a small value range, counting occurrences and using the cumulative counts to directly place the numbers in the result, updating the counts as it goes.
  51. Merge sort divides the list in half to create two unsorted lists. These two unsorted lists are sorted and merged by continually calling the merge-sort algorithm, until you get a list of size 1. The space complexity is O(n) for arrays and O(ln n) for linked lists. The best, average, and worst case times are all O(n*lnn).
  52. Merge sort is a good choice when the data set is too large to fit into the memory. The subsets can be written to disk in separate files until they are small enough to be sorted in memory.
  53. Qucik sort works by choosing a pivot and partitioning the array so that the elements are smaller than the pivot goes to the left. Then, it recursively sorts the left and right parts. It can be shown that always choosing the value in the middle of the set is the best choice for already-sorted data and no worse than most other choices for random unsorted data.
  54. Heap sort is similiar to a selection sort, except that the unsorted region is a heap, so finding the largest element n times gives a logliner runtime.
  55. In a heap, for every node other than the rootm the value of the node is at least (at most) the value of its parent. Thus, the smallest (largest) element is stored at the root and the subtrees rooted at a node contain larger (smaller) values than does the node itself.
  56. The most common searching algorithms are the sequential search and the binary search. If an input array is not sorted, or the input elements are accommodated by dynamic containers (such as linked lists), the search has to be sequential. If the input is a sorted array, the binary search algorithm, is the best choice. If we are allowed to use auxiliary memory, a hash table might help the search, with which a value can be located in O(1) time with a key.
  57. A binary search finds the position of a specified input value (the key) within a sorted array. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match the item’s index, (position) is returned. Otherwise, if the search key is less than the middle element’s key, the algorithm repeats the process in the left subarray; or if the search key is greater, on the right subarray. The algorithm runs on O(ln n).
  58. An array is unimodal if it consists of an increasing sequence followed by a decreasing sequence.
  59. A graph is an abstract network, consisting of nodes (or vertices, V) connected by edges (or arcs, E). A graph can be defined as a pair of sets, G = (V, E), where the node set V is any finite set, and the edge set E is a set of node pairs.
  60. If a graph has no dorection, it is referred as undirected. In this case, nodes with an edge between them are adjacent and adjacent nodes are neighbors.
  61. A subgraph of G consists of a subset of V and E. A spanning subgraph contains all the nodes of the original graph.
  62. If all the nodes in a graph are pairewise adjacent, the grap is called complete.
  63. A pth in G is a subgraph where the edges connect the nodes in a sequence, without revisiting any node. In a directed graph, a path has to follow the directions of the edges.
  64. A walk is an alternating sequence of nodes and edges that allow nodes and edges to be visited multiple times.
  65. A cycle is like a path except that the last edge links the last node to the first.
  66. The length of a path or walk is the value given by its edge count.
  67. In adjacement matrices, instead of listing all the neighours for each node, we have one row with one position for each possible neighbour, filled with True and False values.
  68. While in a graph there may be multiple references to any given node; in a tree each node (data element) is referenced only by at most one other node, the parent node. The root node is the node that has no parent. The nodes referenced by a parent node are called cjildren. A tree is said to be full and complete if all of its leaves are at the bottom and all of the non-leaf nodes have exactly two children.
  69. The height (or depth) of a tree is the length of the path from the root to the deepest node in the tree. It is equal to the maximum level of any node in the tree.
  70. The level (or depth) of a node is the length of path from the root to this node.
  71. Binary trees are tree data structures where each node has at most two child nodes: the lefft and the right. Child nodes may contain references to their parents.
  72. Depth-first search(DFS), are algorithms that searches deeper first in a graph or a tree.
  73. Breath-first search (BFS), are algorithms that yields the values of all nodes of a particular depth before going to any deeper node.
    原文作者:bluescorpio
    原文地址: https://www.jianshu.com/p/94ec68ccb408
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞