八、Python的函数编程(之二)

八、Python的函数编程(之二)

----From a high school student's view to learn Python

 

关键字:

python 高中生学编程 MIT公开课视频 Python函数编程 递归 递归函数 递归调用



四、Python’s Built-in Functions


Python包含了很多内置的函数:

int()float()len()type()range()print()input()abs()str()tuple()

在Python.org上有详细的描述


Built-in Functions

abs()

divmod()

input()

open()

staticmethod()

all()

enumerate()

int()

ord()

str()

any()

eval_r()

isinstance()

pow()

sum()

basestring()

execfile()

issubclass()

print()

super()

bin()

file()

iter()

property()

tuple()

bool()

filter()

len()

range()

type()

bytearray()

float()

list()

raw_input()

unichr()

callable()

format()

locals()

reduce()

unicode()

chr()

frozenset()

long()

reload()

vars()

classmethod()

getattr()

map()

repr()

xrange()

cmp()

globals()

max()

reversed()

zip()

compile()

hasattr()

memoryview()

round()

__import__()

complex()

hash()

min()

set()

apply()

delattr()

help()

next()

setattr()

buffer()

dict()

hex()

object()

slice()

coerce()

dir()

id()

oct()

sorted()

intern()



这些函数多数都不是经常用到,所以大致了解一下即可,有一些印象,在需要的时候再仔细看看说明。

但在开头列的那几个函数,使用度非常高,应该仔细掌握,主要从以下几个方面进行了解:

函数的作用是什么?

函数的参数是什么类型、缺省参数是什么?

函数的返回值是什么类型?



dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  1. If the object is a module object, the list contains the names of the module’s attributes.
  2. If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  3. Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

>>>

>>> import struct 

>>> dir()   # show the names in the module namespace 

['__builtins__', '__doc__', '__name__', 'struct'] 

>>> dir(struct)   # show the names in the struct module 

['Struct', '__builtins__', '__doc__', '__file__', '__name__',  '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',  'unpack', 'unpack_from'] 

>>> class Shape(object):         

def __dir__(self):             

return ['area', 'perimeter', 'location'] 

>>> s = Shape() 

>>> dir(s) 

['area', 'perimeter', 'location'] 

Note

 

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.


这是在一本书上找的两个练习:


1. dir()内建函数

  • Python 交互式解器, 通直接入 dir() 回行 dir() 内建函数。你看到 什么? 示你看到的每一个列表元素的,实际值和你想像的
  • 你会, dir() 函数是干什么的?我知道在 dir 后加上一括号可以行 dir() 内建函数, 如果不加括号会如何? 。 解器返回你什么信息? 你认为这个信息表 示什么意思 ?
  • type() 内建函数接收任意的 Python 象做参数并返回他型。 在解器中 入 type(dir), 看看你得到的是什
  • 练习的最后一部分, 我来瞧一瞧 Python 的文档字符串。 通 dir.__doc__ 可以访问 dir() 内建函数的文档字符串。print dir.__doc__可以个字符串的内容。 多内建 函数,方法,模及模属性都有相的文档字符串。我希望你在你的代中也要写文档 字符串, 它会使用些代的人提供及方便的帮助。


2. 利用 dir() 找出 sys 模中更多的西。

  1. Python交互解器, 行dir()函数,然后入 import sys 以入 sys 模。 再次行 dir() 函数以确 sys 模被正确的入。 然后行 dir(sys) , 你就可以看到 sys 模的所有属性了。
  2. 示 sys 模的版本号属性及平台量。住在属性名前一定要加 sys. ,表示个属性是 sys 模的。其中 version 量保存着你使用的 Python 解器版本, platform 属性包含你运行 Python 使用的算机平台信息。
  3. 最后, 用 sys.exit() 函数。 是一种热键之外的另一种退出 Python 解器的方式。



五、常用内建函数的使用


我们先从一些实际的例子着手:



>>> s = 'Hello, world.'

>>> str(s)

'Hello, world.'

>>> repr(s)

"'Hello, world.'"

>>> str(0.1)

'0.1'

>>> repr(0.1)

'0.10000000000000001'

>>> x = 10 * 3.25

>>> y = 200 * 200

>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'

>>> print s

The value of x is 32.5, and y is 40000...

>>> # The repr() of a string adds string quotes and backslashes:

... hello = 'hello, world\n'

>>> hellos = repr(hello)

>>> print hellos

'hello, world\n'

>>> # The argument to repr() may be any Python object:

... repr((x, y, ('spam', 'eggs')))

"(32.5, 40000, ('spam', 'eggs'))"




how do you convert values to strings? Luckily, Python has ways to convert any value to a string: pass it to the repr() or str() functions.


The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and floating point numbers, in particular, have two distinct representations.


Here are two ways to write a table of squares and cubes:


>>> for x in range(1, 11):

...     print repr(x).rjust(2), repr(x*x).rjust(3),

...     # Note trailing comma on previous line

...     print repr(x*x*x).rjust(4)

...

 1     1

 2     8

 3   9   27

  16   64

  25  125

  36  216

  49  343

  64  512

  81  729

10 100 1000


>>> for x in range(1,11):

...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

...

 1     1

 2     8

 3   9   27

  16   64

  25  125

  36  216

  49  343

  64  512

  81  729

10 100 1000

使用print进行格式化的结果输出,注意print、range等函数的使用


常用函数:

abs(x)

Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.


all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:


def all(iterable):

    for element in iterable:

        if not element:

            return False

    return True


any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:


def any(iterable):

    for element in iterable:

        if element:

            return True

    return False

New in version 2.5.


bin(x)

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.


New in version 2.6.


bool([x])

Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.


New in version 2.2.1.


Changed in version 2.3: If no argument is given, this function returns False.


cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.


complex([real[, imag]])

Create a complex number with the value real + imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, returns 0j.


The complex type is described in Numeric Types — int, float, long, complex.


dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.


If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.


If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().


The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:


If the object is a module object, the list contains the names of the module’s attributes.

If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.

Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:


>>> import struct

>>> dir()   # doctest: +SKIP

['__builtins__', '__doc__', '__name__', 'struct']

>>> dir(struct)   # doctest: +NORMALIZE_WHITESPACE

['Struct', '__builtins__', '__doc__', '__file__', '__name__',

 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',

 'unpack', 'unpack_from']

>>> class Foo(object):

...     def __dir__(self):

...         return ["kan", "ga", "roo"]

...

>>> f = Foo()

>>> dir(f)

['ga', 'kan', 'roo']

Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.


divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).


Changed in version 2.3: Using divmod() with complex numbers is deprecated.


enumerate(sequence[, start=0])

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), .... For example:


>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):

...     print i, season

0 Spring

1 Summer

2 Fall

3 Winter

New in version 2.3.


New in version 2.6: The start parameter.


float([x])

Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number, possibly embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf. Otherwise, the argument may be a plain or long integer or a floating point number, and a floating point number with the same value (within Python’s floating point precision) is returned. If no argument is given, returns 0.0.


Note When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. Float accepts the strings nan, inf and -inf for NaN and positive or negative infinity. The case and a leading + are ignored as well as a leading - is ignored for NaN. Float always represents NaN and infinity as nan, inf or -inf.

The float type is described in Numeric Types — int, float, long, complex.


help([object])

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.


This function is added to the built-in namespace by the site module.


New in version 2.2.


hex(x)

Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.


Note To obtain a hexadecimal string representation for a float, use the float.hex() method.

Changed in version 2.4: Formerly only returned an unsigned literal.


int([x[, base]])

Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace. The base parameter gives the base for the conversion (which is 10 by default) and may be any integer in the range [2, 36], or zero. If base is zero, the proper radix is determined based on the contents of string; the interpretation is the same as for integer literals. (See Numeric literals.) If base is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. If no arguments are given, returns 0.


The integer type is described in Numeric Types — int, float, long, complex.


len(s)

Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

list([iterable])

Return a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, [].


list is a mutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, buffer, xrange. For other containers see the built in dict, set, and tuple classes, and the collections module.


max(iterable[, args...][, key])

With a single argument iterable, return the largest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments.


The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)).


Changed in version 2.5: Added support for the optional key argument.


min(iterable[, args...][, key])

With a single argument iterable, return the smallest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments.


The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if supplied, must be in keyword form (for example, min(a,b,c,key=func)).


Changed in version 2.5: Added support for the optional key argument.


oct(x)

Convert an integer number (of any size) to an octal string. The result is a valid Python expression.


Changed in version 2.4: Formerly only returned an unsigned literal.


print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])

Print object(s) to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.


All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no object is given, print() will just write end.


The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.


Note This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from __future__ import print_function

New in version 2.6.


range([start], stop[, step])

This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:


>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(1, 11)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> range(0, 30, 5)

[0, 5, 10, 15, 20, 25]

>>> range(0, 10, 3)

[0, 3, 6, 9]

>>> range(0, -10, -1)

[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

>>> range(0)

[]

>>> range(1, 0)

[]


raw_input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:


>>> s = raw_input('--> ')

--> Monty Python's Flying Circus

>>> s

"Monty Python's Flying Circus"

If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.


repr(object)

Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval_r(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.


reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).


New in version 2.4.


Changed in version 2.6: Added the possibility to write a custom __reversed__() method.


round(x[, n])

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).


sorted(iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.


The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).


cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.


key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.


reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.


In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. To convert an old-style cmp function to a key function, see the CmpToKey recipe in the ASPN cookbook.


New in version 2.4.


str([object])

Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval_r(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.


For more information on strings see Sequence Types — str, unicode, list, tuple, buffer, xrange which describes sequence functionality (strings are sequences), and also the string-specific methods described in the String Methods section. To output formatted strings use template strings or the % operator described in the String Formatting Operations section. In addition see the String Services section. See also unicode().


sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ''.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) To add floating point values with extended precision, see math.fsum().


New in version 2.3.


tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items. iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is given, returns a new empty tuple, ().


tuple is an immutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, buffer, xrange. For other containers see the built in dict, list, and set classes, and the collections module.


type(object)

Return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.


With three arguments, type() functions as a constructor as detailed below.


xrange([start], stop[, step])

This function is very similar to range(), but returns an “xrange object” instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with break).


CPython implementation detail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1)//step).



六、递归

------

如果函数包含了对其自身的调用,该函数就是递归的。如果一个新的调用能在相同过程中较早的调用结束之前开始,那么该过程就是递归的。

可以看一段MIT公开课视频:

 

递归广泛地应用于使用递归函数的数学应用中,类似数学归纳法。

拿阶乘函数的定义来说明:

N! == factorial(N) == 1 * 2 * 3 ... * N 

我们可以用这种方式来看阶乘:

    factorial(N) = N!

    = N * (N-1)!

    = N * (N-1) * (N-2)!

   

    = N * (N-1) * (N-2) ... * 3 * 2 * 1

我们现在可以看到阶乘是递归的,因为 

factorial(N) = N* factorial(N-1)

换句话说,为了获得 factorial(N)的值,需要计算 factorial(N-1),而且,为了找到 factorial(N-1),需要计算 factorial(N-2)等等。我们现在给出阶乘函数的递归版本。

>>> def factorial(n):

...     if n==0 or n==1:

...             return 1

...     else:

...             return n*factorial(n-1)

... 

>>> factorial(21)

51090942171709440000L

>>> factorial(4)

24

>>> factorial(1)

1

>>> factorial(0)

1


特别强调:

  1. 递归函数必须有一个终止执行的条件,如我们的例子中,当n=0或者n=1时,会终止;否则,程序将进入一个无限循环的状态,俗称“死循环”
  2. 递归虽然使程序看起来非常的简单,但是递归程序如果递归的次数很大的话,将会严重的消耗计算机的内存,甚至可能导致系统的崩溃


下面给出一段视频,里面是以经典的递归问题:斐波那契数列作为例子进行讲解的,值得学习!

【插入视频】

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值