《Think Python》(2):递归、迭代、字符串、搜索

第五章 条件和递归

  • 无限递归时会报错:RuntimeError: Maximum recursion depth exceeded
  • input():返回的是float或int,而raw_input():返回的是str,实际上input = eval(raw_input())
  • int(“12.2”)是无法起作用的,如果想把输入的数字转成整形可以直接用int(input(x)),也可以用int(float(raw_input()))。简而言之,int只能把浮点或者整数形式的str转成整数,无法把浮点形式的str转成整数。
  • 嵌套条件语句会很快随着嵌套层数增多而变得非常难阅读,通常可以用逻辑操作符来简化嵌套条件语句。

第六章 有返回函数

  • 增量开发的关键点:

    1. 以一个可以正确运行的程序开始,每次只做小的增量修改。如果在任意时刻发现错误,你都应当知道错误在哪里;
    2. 使用临时变量保存计算的中间结果,这样你可以显示和检查它们;
    3. 一旦整个程序完成,你可能会想要删除掉某些脚手架代码或者把多个语句综合到一个复杂的表达式中。但只在不会增加代码阅读的难度时才应该那么做。
  • 再谈递归——“坚持信念”:当你遇到一个函数调用时,不去跟踪执行的流程,而假定函数是正确工作,能够返回正确的结果。

  • 递归调试举例:
    def factorial(n):
    space = ‘ ‘  (4  n)
    print space, ‘factorial’, n
    if n == 0:
    print space, 'returing 1'
    return 1
    
    else:
    recurse = factorial(n-1)
    result = n * recurse
    print space, 'returing', result
    return result
    

“””factorial(5) output factorial 5 factorial 4 factorial 3 factorial 2 factorial 1 factorial 0 returing 1 returing 1 returing 2 returing 6 returing 24 returing 120 “””

第7章 迭代

  • 初始化、增量、跳出

第8章 字符串

  • 字符串是不可变的:你不能修改一个已经存在的字符串。你能做的最多是新建一个字符串,它和原来的字符串稍有不同。
  • in是一个布尔操作符,操作于两个字符串上,如果第一个是第二个的子串,则返回True,否则返回False。
  • str[index]:index为下标,从0开始到len(str)-1为止,str[-1]表示倒数第一个字母。
  • str[n:m]:返回下标n~m的字母。

第9章 案例分析:文字游戏

#Chapter 9 Words Game
#Exercise 9-1
def print_word():
    fin = open('words.txt')
    for line in fin:
        word = line.strip()
        if len(word) > 20:
            print word

#Exercise 9-2
def has_no_e(word):
    if 'e' in word:
        return False
    else:
        return True

def print_no_e():
    fin = open('words.txt')
    sum = 0
    sum_e = 0
    for line in fin:
        word = line.strip()
        if has_no_e(word):
            print word
            sum_e = sum_e + 1
        sum = sum + 1
    print float(sum_e)/sum

#Exercise 9-3
def avoids(word, str):
    for letter in word:
        if letter in str:
            return False
    return True

#Exercise 9-4
def uses_only(word, str):
    for letter in word:
        if letter not in str:
            return False
    return True

#Exercise 9-5 
def use_all(word, required):
    for letter in required:
        if letter not in word:
            return False
    return True

#Exercise 9-6
def is_abecedarian(word):
    i = 0
    while i < len(word)-1:
        if word[i+1] < word[i]:
            return False
        i = i+1
    return True  

#Exercise 9-7
def is_triple(word):
    i = 0
    count = 0
    while i < len(word)-1:
        if word[i] == word[i+1]:
            count = count + 1
            if count == 3:
                return True
            i = i + 2
        else:
            count = 0
            i = i + 1
    return False

def print_triple():
    fin = open('words.txt')
    for line in fin:
        word = line.strip()
        if is_triple(word):
            print word

#Exercise 9-8
def is_huiwen(num, start, len):
    s = str(num)[start:start+len]
    return s[::-1] ==s

def check(i):
    return (is_huiwen(i, 2, 4) and is_huiwen(i+1, 1, 5) and is_huiwen(i+2, 1, 4) and is_huiwen(i+3, 0, 6))

def print_huiwen():
    i = 100000
    while i < 999999:
        if check(i):
            print i
        i = i + 1

#Exercise 9-9
def str_fill(i, len):
    """return the integer (i) written as a string with at least
    (len) digits"""
    return str(i).zfill(len)

def are_reversed(i, j):
    """ return True if the integers i and j, written as strings,
    are the reverse of each other"""
    return str_fill(i,2) == str_fill(j,2)[::-1]

def num_instances(diff, flag=False):
    """returns the number of times the mother and daughter have
    pallindromic ages in their lives, given the difference in age.
    If flag==True, prints the details."""
    daughter = 0
    count = 0
    while True:
        mother = daughter + diff
        if are_reversed(daughter, mother) or are_reversed(daughter, mother+1):
            count = count + 1
            if flag:
                print daughter, mother
        if mother > 120:
            break
        daughter = daughter + 1
    return count

def check_diffs():
    """enumerate the possible differences in age between mother
    and daughter, and for each difference, count the number of times
    over their lives they will have ages that are the reverse of
    each other."""
    diff = 10
    while diff < 70:
        n = num_instances(diff)
        if n > 0:
            print diff, n
        diff = diff + 1
"""
print 'diff  #instances'
check_diffs()

print
print 'daughter  mother'
num_instances(18, True)
"""

小结

Visual Studio 2013 TestVisual Studio真是神器,调试太好用了,太方便了。变量监控,输出都在这边,还有交互式界面可以输python代码,太方面了。微软大法好啊