YuXingY 发表于2年前

• 发表于 2年前
• 阅读 3
• 收藏 0
• 评论 0

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)``````

×