笔记是我看《Data Structures & Algorithms》一书的记录,包括书上内容的摘抄、书上的示例源代码和自己做的习题源代码。重新学习的主要目的就是系统复习一下python基础知识、常用数据结构和算法,把它们整理到一起便于自己查找。
一、 Python编程基础
1.笔记
1.1 python内置的类
类型 | 描述 | immutable |
---|---|---|
bool | Boolean value | 是 |
int | integer (arbitrary magnitude) | 是 |
float | floating-point number | 是 |
list | mutable sequence of objects | 否 |
tuple | immutable sequence of objects | 是 |
str | character string | 是 |
set | unordered set of distinct objects | 否 |
frozenset | immutable form of set class | 是 |
dict | associative mapping | 否 |
1.2操作符优先顺序
type | symbols | |
1 | member access | expr.member |
2 | function/method calls container subscripts/slices | expr(...) expr[...] |
3 | exponentiation | ** |
4 | unary operators | +expr, −expr, ̃expr |
5 | multiplication, division | *, /, //, % |
6 | addition, subtraction | +, − |
7 | bitwise shifting | <<, >> |
8 | bitwise-and | & |
9 | bitwise-xor | ˆ |
10 | bitwise-or | | |
11 | comparisons containment | is, is not, ==, !=, <, <=, >, >= in, not in |
12 | logical-not | not expr |
13 | logical-and | and |
14 | logical-or | or |
15 | conditional | val1 if cond else val2 |
16 | assignments | =, +=, −=, =, etc. |
Calling Syntax | Description | |
1 | abs(x) | Return the absolute value of a number. |
2 | all(iterable) | Return True if bool(e) is True for each element e. |
3 | any(iterable) | Return True if bool(e) is True for at least one element e. |
4 | chr(integer) | Return a one-character string with the given Unicode code point. |
5 | divmod(x, y) | Return (x // y, x % y) as tuple, if x and y are integers. |
6 | hash(obj) | Return an integer hash value for the object (see Chapter 10). |
7 | id(obj) | Return the unique integer serving as an “identity” for the object. |
8 | input(prompt) | Return a string from standard input; the prompt is optional. |
9 | isinstance(obj, cls) | Determine if obj is an instance of the class (or a subclass). |
10 | iter(iterable) | Return a new iterator object for the parameter (see Section 1.8). |
11 | len(iterable) | Return the number of elements in the given iteration. |
12 | map(f, iter1, iter2, ...) | Return an iterator yielding the result of function calls f(e1, e2, ...) for respective elements e1 ∈ iter1, e2 ∈ iter2, ... |
13 | max(iterable) | Return the largest element of the given iteration. |
14 | max(a, b, c, ...) | Return the largest of the arguments. |
15 | min(iterable) | Return the smallest element of the given iteration. |
16 | min(a, b, c, ...) | Return the smallest of the arguments. |
17 | next(iterator) | Return the next element reported by the iterator (see Section 1.8). |
18 | open(filename, mode) | Open a file with the given name and access mode. |
19 | ord(char) | Open a file with the given name and access mode. |
20 | pow(x, y) | Return the value x y (as an integer if x and y are integers); equivalent to x**y. |
21 | pow(x, y, z) | Return the value (x y mod z) as an integer. |
22 | print(obj1, obj2, ...) | Print the arguments, with separating spaces and trailing newline. |
23 | range(stop) | Construct an iteration of values 0, 1, . . . , stop − 1. |
24 | range(start, stop) | Construct an iteration of values start, start + 1, . . . , stop − 1. |
25 | range(start, stop, step) | Construct an iteration of values start, start + step, start + 2 step, . . . |
26 | reversed(sequence) | Return an iteration of the sequence in reverse. |
27 | round(x) | Return the nearest int value (a tie is broken toward the even value). |
28 | round(x, k) | Return the value rounded to the nearest 10 − k (return-type matches x). |
29 | sorted(iterable) | Return a list containing elements of the iterable in sorted order. |
30 | sum(iterable) | Return the sum of the elements in the iterable (must be numeric). |
31 | type(obj) | Return the class to which the instance obj belongs. |
通过input和print来实现与控制台交互,如果是整数或实数,输入的字符串用 int或float等转换,示例代码
#简单输入输出
age = int(input('Enter your age in years: '))
max_heart_rate = 206.9 - (0.67*age) # as per Med Sci Sports Exerc.
target = 0.65 * max_heart_rate
print('Your target fat-burning heart rate is ', target)
输出
Enter your age in years: 42
('Your target fat-burning heart rate is ', 116.194)
文件输入输出
用内置命令open打开文件,如 fp = open('sample.txt'),关闭文件则用fp.close()。文件常用的操作如下:
fp.read()
fp.read(k)
fp.readline()
fp.readlines()
for line in fp
fp.seek(k)
fp.tell()
fp.write(string)
fp.writelines(seq)
print(...,file=fp) 重定向
1.5 异常处理
class | Description | |
1 | Exception | A base class for most error types |
2 | AttributeError | Raised by syntax obj.foo, if obj has no member named foo |
3 | EOFError | Raised if “end of file” reached for console or file input |
4 | IOError | Raised upon failure of I/O operation (e.g., opening file) |
5 | IndexError | Raised if index to sequence is out of bounds |
6 | KeyError | Raised if nonexistent key requested for set or dictionary |
7 | KeyboardInterrupt | Raised if user types ctrl-C while program is executing |
8 | NameError | Raised if nonexistent identifier used |
9 | StopIteration | Raised by next(iterator) if no element; see Section 1.8 |
10 | TypeError | Raised when wrong type of parameter is sent to a function |
11 | ValueError | Raised when parameter has invalid value (e.g., sqrt(−5)) |
12 | ZeroDivisionError | Raised when any division operator used with 0 as divisor |
抛出异常、捕获异常示例
raise ValueError('x cannot be negative')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-4edb40978c90> in <module>()
----> 1 raise ValueError('x cannot be negative')
ValueError: x cannot be negative
x = 20
y = 0
try:
ratio = x / y
except ZeroDivisionError:
print 'y cannot be 0'
y cannot be 0
1.6 一些简便写法
expr1 if condition else expr2
if n >= 0:
param = n
else:
param = −n
result = foo(param)
# call the function
param = n if n >= 0 else −n
result = foo(param)
# pick the appropriate value
# call the function
result = foo(n if n >= 0 else −n)
[ expression for value in iterable if condition ]
result = [ ]
for value in iterable:
if condition:
result.append(expression)
squares = [ ]
for k in range(1, n+1):
squares.append(k k)
squares = [k k for k in range(1, n+1)]
factors = [k for k in range(1,n+1) if n % k == 0]
[ k k for k in range(1, n+1) ] #list comprehension
{ k k for k in range(1, n+1) } #set comprehension
( k k for k in range(1, n+1) ) #generator comprehension
{ k : k k for k in range(1, n+1) } #dictionary comprehension
二、面向对象编程
2.1类定义
类定义包括member function 和 attribbutes(fields, instance variable, data members)。class关键字、self标识符、以_开头相当于protected、以__开头表相当于private、__init__。示例源代码
class CreditCard:
"""A consumer credit card."""
def __init__ (self, customer, bank, acnt, limit):
"""Create a new credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., John Bowman )
bank the name of the bank (e.g., California Savings )
acnt the acount identifier (e.g., 5391 0375 9387 5309 )
limit credit limit (measured in dollars)
"""
self._customer = customer
self._bank = bank
self._account = acnt
self._limit = limit
self._balance = 0
def get_customer(self):
"""Return name of the customer."""
return self._customer
def get_bank(self):
"""Return the bank s name."""
return self._bank
def get_account(self):
"""Return the card identifying number (typically stored as a string)."""
return self._account
def get_limit(self):
"""Return current credit limit."""
return self._limit
def get_balance(self):
"""Return current balance."""
return self._balance
def charge(self, price):
"""Charge given price to the card, assuming sufficient credit limit.
Return True if charge was processed; False if charge was denied.
"""
if price + self._balance > self._limit: # if charge would exceed limit,
return False # cannot accept charge
else:
self._balance += price
return True
def make_payment(self, amount):
"""Process customer payment that reduces balance."""
self._balance -= amount
if __name__ == '__main__' :
wallet = [ ]
wallet.append(CreditCard( 'John Bowman ', 'California Savings' ,
'5391 0375 9387 5309' , 2500) )
wallet.append(CreditCard('John Bowman' , 'California Federal' ,
'3485 0399 3395 1954' , 3500) )
wallet.append(CreditCard( 'John Bowman' , 'California Finance' ,
'5391 0375 9387 5309' , 5000) )
for val in range(1, 17):
wallet[0].charge(val)
wallet[1].charge(2*val)
wallet[2].charge(3*val)
for c in range(3):
print(' Customer = ', wallet[c].get_customer( ))
print(' Bank = ', wallet[c].get_bank( ))
print(' Account = ', wallet[c].get_account( ))
print(' Limit = ', wallet[c].get_limit( ))
print(' Balance = ', wallet[c].get_balance( ))
while wallet[c].get_balance( ) > 100:
wallet[c].make_payment(100)
print(' New balance = ', wallet[c].get_balance( ))
print
操作符重载是通过重载特定的函数实现的,比如 + 对应 __add__
2.2 继承
添加新的属性、覆盖父类的方法、调用父类的方法
class PredatoryCreditCard(CreditCard):
"""An extension to CreditCard that compounds interest and fees."""
def __init__(self, customer, bank, acnt, limit, apr):
"""Create a new predatory credit card instance.
The initial balance is zero.
customer the name of the customer (e.g., John Bowman )
bank the name of the bank (e.g., California Savings )
acnt the acount identifier (e.g., 5391 0375 9387 5309 )
limit credit limit (measured in dollars)
apr annual percentage rate (e.g., 0.0825 for 8.25% APR)
"""
CreditCard.__init__(self,customer, bank, acnt, limit) # call super constructor
self._apr = apr
def charge(self, price):
"""Charge given price to the card, assuming sufficient credit limit.
Return True if charge was processed.
Return False and assess 5 fee if charge is denied.
"""
success = CreditCard.charge(self, price) # call inherited method
if not success:
self._balance += 5 # assess penalty
return success # caller expects return value
def process_month(self):
"""Assess monthly interest on outstanding balance."""
if self._balance > 0:
# if positive balance, convert APR to monthly multiplicative factor
monthly_factor = pow(1 + self._apr, 1/12)
self._balance = monthly_factor
三、算法复杂度