Rapid GUI Programming with Python and Qt第二章习题答案加注释

2.1

def valid(text, chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
    result = []
    for char in text:
        if char in chars:
            result.append(char)              # append() : 在List末尾添加元素
    return "".join(result)                  # List->Str 的最简单方法之一

2.2

def charcount(text):
    stats = {}
    for char in "abcdefghijklmnopqrstuvwxyz":
        stats[char] = 0
    stats["whitespace"] = 0
    stats["others"] = 0
    for char in text.lower():
        if char in stats:
            stats[char] += 1
        elif char.isspace():
            stats["whitespace"] += 1
        else:
            stats["others"] += 1
    return stats
'''
如果想不显示key为0的单位,可以使用setdefault()函数
'''

2.3

def integer(number):
    try:
        x = int(round(float(number)))
    except ValueError:
        x = 0
    return x
'''
很简洁的写法
float()可以将int,float,str都转为float
round()的作用是四舍五入到小数点后某几位,正常的用法是round(float, n),结果仍为float
int()将结果转为整形
'''

2.4

def incrementString(text="AAAA"):
    if not text.isalpha():
        raise ValueError
    value= [ord(c) for c in reversed(text)]
    value[0]+=1
    i=0
    while value[i]> ord('Z'):
        value[i]= ord('A')
        try:
            i+=1
            value[i]+=1
        except IndexError, e:
            value.append(ord('A'))
            return "".join(chr(x) for x in reversed(value))
    return "".join(chr(x) for x in reversed(value))
'''
这道题比较复杂,自己稍微写了一下
通过ord()将字符串转化为ASCLL码,结合reversed()反转,这样字母的变换可以用简单的加1来完成
通过chr()将ASCLL码还原为字符串
字符串的末尾由IndexError来判断
'''

if not text.isalpha():
        raise ValueError, "text must be purely alphabetic"
    OrdA = ord("A")
    OrdZ = ord("Z")
    changed = False
    values = [ord(c) for c in reversed(text.upper())]
    for i in range(len(values)):
        if values[i] < OrdZ:
            values[i] += 1
            changed = True
            break
        elif values[i] == OrdZ:
            values[i] = OrdA
    if not changed:
        values = [OrdA] + values
    return "".join([chr(v) for v in reversed(values)])
'''
官方答案,字符串的结尾由len()来得到,没有使用异常处理
changed是进位信息,代码更简洁些
'''

2.5

def leapyears(yearlist):
    for year in yearlist:
        if year % 4 == 0:
            if year % 100 == 0 and not year % 400 == 0:
                continue
            yield year
'''
官方答案,很简洁
生成器需要用到yield指令
'''

你可能感兴趣的:(python,Rapid,GUI,Programming,with,Python,and,Qt)