[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.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,559评论 0 23
  • “人有悲欢离合,月有阴晴圆缺。”一个圆月,两个月牙,就像人的感情一样,一半付出,一半等待。 夜再一次来临,我紧了紧...
    金娜娜阅读 562评论 1 2
  • 沉重的脑袋不断下坠 坠入前赴后继的梦魇 努力爬出一个深渊 落入另外一个黑洞 地狱的绳索不肯放松 命运的脚踝勒出血痕...
    秋未完阅读 326评论 4 6
  • 软件版本:3.5.1 设备型号:iPhone5S 操作系统:ios8.1 作为一个听歌党,每天除了微信,打开使用最...
    斑丘阅读 6,565评论 0 6