《python笔记》廖雪峰Python3习题

  • 1.利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']
def f(s):
    s=s[0].upper()+s[1:].lower()
    return s
L1=['adam', 'LISA', 'barT']
L2=list(map(f,L1))
print(L2)
  • 2.Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
from functools import reduce
def prod(L):
    return reduce(lambda x,y:x*y,L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')
  • 3.利用mapreduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
#coding:utf-8
from functools import reduce

def str2float(s):
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    s = s.split('.')
    s1 = s[0]
    s2 = s[1]
    s = s1 + s2
    def char2num(s):
        return DIGITS[s]
    def f(a, b):
        return a*10 + b
    x=reduce(f,map(char2num,s))/10**len(s2)
    return x

print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')
#方法二
from functools import reduce
def str2float(s):
    def fn(x,y):
        return x*10+y
    n=s.index('.')
    s1=list(map(int,[x for x in s[:n]]))
    s2=list(map(int,[x for x in s[n+1:]]))
    return reduce(fn,s1) + reduce(fn,s2)/10**len(s2)#m**n 这个表达的就是 m 的 n 次方
print('\'123.4567\'=',str2float('123.4567'))  
  • 4.整理成一个str2int的函数就是:
from functools import reduce

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return DIGITS[s]
    return reduce(fn, map(char2num, s))

print(str2int('2'))
  • 5.用filter求素数

计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:

首先,列出从2开始的所有自然数,构造一个序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

不断筛下去,就可以得到所有的素数。


def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def _not_divisible(n):
    return lambda x: x % n >0

def primes():
    yield 2
    it = _odd_iter()
    while True:
      n = next(it)
      yield n
      it = filter(_not_divisible,it)

for n in primes():
    if n < 10:
        print(n)
    else:
        break
  • 6.回数是指从左向右读和从右向左读都是一样的数,例如12321909。请利用filter()筛选出回数:
#方法一
def f(x):
    n=str(x)
    return n==n[::-1]
print(list(filter(f,[m for m in range(1000) if m> 100])))

[101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999]
#方法二
def is_palindrome(n):
    a=str(n)
    for i in range(len(a)):
        if a[i]==a[-i-1]:
            return a
        else:
            return False
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
    print('测试成功!')
else:
    print('测试失败!')
  • 7.假设我们用一组tuple表示学生名字和成绩:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]。请用sorted()对上述列表分别按名字和分数排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
    return t[0]
def by_score(t):
    return t[-1]

L1=sorted(L,key=by_name)
L2=sorted(L,key=by_score,reverse=True)
print('L1=',L1)
print('L2=',L2)
  • 8.利用闭包返回一个计数器函数,每次调用它返回递增整数:

方法一:

def createCounter():
    s = [0]
    def counter():
        s[0] = s[0]+1
        return s[0]
    return counter

counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
    print('测试通过!')
else:
    print('测试失败!')

方法二:

s = 0
def createCounter():
    def counter():
        global s
        s=s+1
        return s
    return counter
counterA = createCounter()
print(counterA(),counterA())

方法三:

def createCounter():
    m=0
    def counter():
        nonlocal m
        m = m + 1
        return m
    return counter

counterX=createCounter()
print(counterX(),counterX())
  • 9.请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:

import time, functools

def printcalltime(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kw):
        start = time.time()
        res = fun(*args,**kw)
        end = time.time()
        print('%s executed in %s ms '%(fun.__name__,(end-start)*1000))
        return res
    return wrapper
@printcalltime
def fast(x,y):
    time.sleep(0.0045)
    return x+y
@printcalltime
def slow(x,y):
    time.sleep(0.1345)
    return x*y

f = fast(11,22)
print(f)
s= slow(11,33)
print(s)

if f != 33:
    print('测试失败')
elif s != 363:
    print('测试失败')
  • 10.为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:
class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1 #每创建一个实例,count就加1


if Student.count != 0:
    print('测试失败!')
else:
    bart = Student('Bart')
    if Student.count != 1:
        print('测试失败!')
    else:
        lisa = Student('Bart')
        if Student.count != 2:
            print('测试失败!')
        else:
            print('Students:', Student.count)
            print('测试通过!')

 

你可能感兴趣的:(python笔记)