核心编程第十一章
博客专区 > YuXingY 的博客 > 博客详情
核心编程第十一章
YuXingY 发表于2年前
核心编程第十一章
  • 发表于 2年前
  • 阅读 2
  • 收藏 0
  • 点赞 2
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

摘要: 部分习题

11-3(a)

def max2(x, y):
	if x >= y:
		return x
	else:
		return y


def min2(x, y):
	if x >= y:
		return y
	else:
		return x

11-3(b)

def my_max(*args):
    if len(args) == 1:
        args = args[0]
    n = args[0]
    for i in args[1:]:
        if i >= n:
            n = i
    return n


def my_min(*args):
    if len(args) == 1:
        args = args[0]
    n = args[0]
    for i in args[1:]:
        if i <= n:
            n = i
    return n

11-4

def swtime(num):
	return divmod(num, 60)
print swtime(280)

11-7

print map(None, [1, 2, 3], ['abc', 'def', 'ghi'])
print zip([1, 2, 3], ['abc', 'def', 'ghi'])

11-8

def comlea(num):
	return (num % 4 == 0 and num % 100 != 0) or num % 400 == 0
		
years = [1998, 2004, 1995, 2010]
print filter(comlea, years)

print [i for i in years if comlea(i)]

11-9

average = lambda x, y: (x + y) / 2
print reduce(average, [1, 2, 3, 4])

11-11

filename = raw_input('your filename')


def cleanup_file(filename):
	f = open(filename)
	lines = map(lambda line: line.strip(' '), f)
	f.close()
	return lines


with open(filename) as f:
	lines = [line.strip(' ') for line in f]


def writefile(ori_file, new_file):
	file2 = open(new_file, 'w')
	lines = cleanup_file(ori_file)
	file2.writelines(lines)
	file2.close()

11-12

import time


def deco(func):
	def timeit():
		time.clock()
		a = func()
		b = time.clock()
		return a, b
	return timeit


@deco
def fu():
	a = 1 + 8
	return a
print fu()


def timeits(func):
	time.clock()
	a = func()
	b = time.clock()
	return a, b

11-13

muls = lambda x, y: x * y
reduce(muls, range(1, 5))


def timeits(func):
	time.clock()
	a = func(4)
	b = time.clock()
	return a, b


def fu(n):
	return reduce(muls, range(1, n + 1))
print timeits(fu)


def mul(num):
	if num == 0 or num == 1:
		return 1
	else:
		return num * mul(num - 1)
print timeits(mul)


def mull(num):
	muls = 1
	for i in range(1, num + 1):
		muls *= i
	return muls
print timeits(mull)

 

共有 人打赏支持
粉丝 0
博文 39
码字总数 18413
×
YuXingY
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: