书中关于算法和运行时间的介绍:
- Informally, an algorithm is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output. An algorithm is thus a sequence of computational steps that transform the input into the output.
- The running time of an algorithm on a particular input is the number of primitive operations or “steps” executed.
1. 排序
python自带的有列表排序方法,sorted(L)方法可以用。
L.sort()时灵时不灵的,不知道为什么。
>>> help(list.sort)
Help on method_descriptor:
sort(...)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
>>>
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
这里可以自己写排序方法。
比如,最简单的这个选择排序法。
(比较两个元素,如果他们的顺序错误,就把他们交换过来。)
def sel_sort(lists):
for i in range(len(lists)):
for j in range(i + 1, len(lists)):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
>>> L = [2, 5, 98, 56, 3, 0]
>>> sel_sort(L)
[0, 2, 3, 5, 56, 98]
>>>
2. 斐波那契数列
斐波那契数列(Fibonacci sequence),又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
注意python中列表索引的第一个数字是0,斐波那契数列从1开始。
这里最主要的是应用了递归的方法,在python函数中使用了函数本身。
def fib(n):
"""Assumes n an int > 0,
returns fibonacci of n"""
if n == 1 or n == 2:
return 1
else:
return fib(n-1)+fib(n-2)
>>> fib(3)
2
>>> fib(6)
8
>>> fib(9)
34
>>>