From c6fb71c8f4d4bd164a00cffe5bbb0dcab691f8de Mon Sep 17 00:00:00 2001 From: Hui Lan Date: Mon, 22 Apr 2019 15:44:08 +0800 Subject: Removed import operator from the function sort_by_nth_element2 as it is not needed --- LectureNotesOnPython.rst | 81 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst index de6e81e..8223567 100644 --- a/LectureNotesOnPython.rst +++ b/LectureNotesOnPython.rst @@ -1171,7 +1171,7 @@ key与value互换 每个py文件就是一个模块。 每个模块有一个隐含的变量指示模块名, ``__name__`` 。 -当该py文件作为主模块运行时, ``__name__`` 的值是 ``__main__`` 。 当该py文件作为被引入的模块时,该模块的 ``__name__`` 的是模块名。 +当该py文件作为主模块运行时, ``__name__`` 的值是 ``__main__`` 。 当该py文件作为被引入的模块时,该模块的 ``__name__`` 的是模块名 (是文件名)。 在每个py文件 ``if __name__ == '__main__':`` 后添加测试代码, 当这个py文件作为主模块运行时,测试代码会被执行。 而当引入这个py文件时,该文件的测试代码不会被执行,我们也不希望它们执行。 @@ -1375,7 +1375,6 @@ Python 自带的排序算法最快, ``selection_sort`` 最慢。 def sort_by_nth_element2(lst, n): ''' Return a sorted list of tuples lst, according to the nth element in each tuple.''' - import operator result = sorted(lst, key=lambda x: x[n]) # https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda return result @@ -1455,6 +1454,84 @@ Python 自带的排序算法最快, ``selection_sort`` 最慢。 +递归 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Memo +`````````````````````````````````````````````````` + +.. code:: python + + def fibonacci(n): + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fibonacci(n-1) + fibonacci(n-2) + + + known = {0:0, 1:1} + def fibonacci_memo(n): + ''' A 'memoized' version of fibonacci. ''' + if n in known: + return known[n] + res = fibonacci(n-1) + fibonacci(n-2) + known[n] = res + return res + + + n = 35 + import time + t1 = time.time() + print(fibonacci(n)) + print('%4.2f' % (time.time() - t1)) + + t1 = time.time() + print(fibonacci_memo(n)) + print('%4.2f' % (time.time() - t1)) + + +用递归方式改写 ``selection_sort`` +``````````````````````````````````````````````````` + +.. code:: python + + def selection_sort(L): + if len(L) <= 1: + return L + + min_val = L[0] + k = j = 0 + while j < len(L): + if L[j] < min_val: + min_val = L[j] + k = j + j += 1 + L[k], L[0] = L[0], L[k] + return [min_val] + selection_sort(L[1:]) + + + +类 class 与 对象 object +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +web 应用程序 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +输入文本 +`````````````````````````````````````````````````` + +school.py + + +上传文件 +``````````````````````````````````````````````````` + +omg + + 参考 ------ -- cgit v1.2.1