python数据结构学习笔记-1

 笔记是我看《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操作符优先顺序

 typesymbols
1member accessexpr.member
2function/method calls
container subscripts/slices
expr(...)
expr[...]
3exponentiation**
4unary operators+expr, −expr,  ̃expr
5multiplication, division*, /, //, %
6addition, subtraction+, −
7bitwise shifting<<, >>
8bitwise-and&
9bitwise-xorˆ
10bitwise-or|
11comparisons
containment
is, is not, ==, !=, <, <=, >, >=
in, not in
12logical-notnot expr
13logical-andand
14logical-oror
15conditionalval1 if cond else val2
16assignments=, +=, −=, =, etc.
1.3常用内置函数

 Calling SyntaxDescription
1abs(x)Return the absolute value of a number.
2all(iterable)Return True if bool(e) is True for each element e.
3any(iterable)Return True if bool(e) is True for at least one element e.
4chr(integer)Return a one-character string with the given Unicode code point.
5divmod(x, y)Return (x // y, x % y) as tuple, if x and y are integers.
6hash(obj)Return an integer hash value for the object (see Chapter 10).
7id(obj)Return the unique integer serving as an “identity” for the object.
8input(prompt)Return a string from standard input; the prompt is optional.
9isinstance(obj, cls)Determine if obj is an instance of the class (or a subclass).
10iter(iterable)Return a new iterator object for the parameter (see Section 1.8).
11len(iterable)Return the number of elements in the given iteration.
12map(f, iter1, iter2, ...)Return an iterator yielding the result of function calls f(e1, e2, ...)
for respective elements e1 ∈ iter1, e2 ∈ iter2, ...
13max(iterable)Return the largest element of the given iteration.
14max(a, b, c, ...)Return the largest of the arguments.
15min(iterable)Return the smallest element of the given iteration.
16min(a, b, c, ...)Return the smallest of the arguments.
17next(iterator)Return the next element reported by the iterator (see Section 1.8).
18open(filename, mode)Open a file with the given name and access mode.
19ord(char)Open a file with the given name and access mode.
20pow(x, y)Return the value x y (as an integer if x and y are integers);
equivalent to x**y.
21pow(x, y, z)Return the value (x y mod z) as an integer.
22print(obj1, obj2, ...)Print the arguments, with separating spaces and trailing newline.
23range(stop)Construct an iteration of values 0, 1, . . . , stop − 1.
24range(start, stop)Construct an iteration of values start, start + 1, . . . , stop − 1.
25range(start, stop, step)Construct an iteration of values start, start + step, start + 2 step, . . .
26reversed(sequence)Return an iteration of the sequence in reverse.
27round(x)Return the nearest int value (a tie is broken toward the even value).
28round(x, k)Return the value rounded to the nearest 10 − k (return-type matches x).
29sorted(iterable)Return a list containing elements of the iterable in sorted order.
30sum(iterable)Return the sum of the elements in the iterable (must be numeric).
31type(obj)Return the class to which the instance obj belongs.
1.4简单输入输出

通过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 异常处理

 classDescription
1ExceptionA base class for most error types
2AttributeErrorRaised by syntax obj.foo, if obj has no member named foo
3EOFErrorRaised if “end of file” reached for console or file input
4IOErrorRaised upon failure of I/O operation (e.g., opening file)
5IndexErrorRaised if index to sequence is out of bounds
6KeyErrorRaised if nonexistent key requested for set or dictionary
7KeyboardInterruptRaised if user types ctrl-C while program is executing
8NameErrorRaised if nonexistent identifier used
9StopIterationRaised by next(iterator) if no element; see Section 1.8
10TypeErrorRaised when wrong type of parameter is sent to a function
11ValueErrorRaised when parameter has invalid value (e.g., sqrt(−5))
12ZeroDivisionErrorRaised 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

三、算法复杂度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python学习笔记》是由皮大庆编写的一本关于Python语言学习的教材。在这本书中,作者详细介绍了Python语言的基础知识、语法规则以及常用的编程技巧。 首先,作者简要介绍了Python语言的特点和优势。他提到,Python是一种易于学习和使用的编程语言,受到了广大程序员的喜爱。Python具有简洁、清晰的语法结构,使得代码可读性极高,同时也提供了丰富的库和模块,能够快速实现各种功能。 接着,作者详细讲解了Python的基本语法。他从变量、数据类型、运算符等基础知识开始,逐步介绍了条件语句、循环控制、函数、模块等高级概念。同时,作者通过大量的示例代码和实践案例,帮助读者加深对Python编程的理解和应用。 在书中,作者还特别强调了编写规范和良好的编程习惯。他从命名规范、注释风格、代码缩进等方面指导读者如何写出清晰、可读性强的Python代码。作者认为,良好的编程习惯对于提高代码质量和提高工作效率非常重要。 此外,作者还介绍了Python的常用库和模块。他提到了一些常用的库,如Numpy、Pandas、Matplotlib等。这些库在数据处理、科学计算、可视化等领域有广泛的应用,帮助读者更好地解决实际问题。 总的来说,《Python学习笔记》是一本非常实用和全面的Python学习教材。通过学习这本书,读者可以系统地学习和掌握Python编程的基础知识和高级应用技巧,为以后的编程学习和工作打下坚实的基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值