11-4
def time_in_minues(minues):
print '%d minues' % minues
def minues2h_and_m():
minue = minues % 60
hours = minues // 60
return '%d : %d' % (hours, minue)
return minues2h_and_m
time = time_in_minues(601)
print time()
11-7
print map(None, [1,2,3],['abc','def','ghi'])
print zip([1,2,
11-8
print filter(lambda year: year % 4 == 0 and year % 100 != 0 or year % 400 == 0,
[year for year in range(1900, 2016)])
print [year for year in range(1900, 2016) if year % 4 == 0
and year % 100 != 0 or year % 400 == 0]
11-9
def average(num):
return reduce((lambda x, y: x + y), range(num+1))/num
print average(5)
11-11
def create(filename):
f = open(filename, 'r')
nf = open('newfile.txt', 'w')
flines = [line.strip() for line in f]
for line in flines:
nf.write(line)
nf.write('\n')
f.close()
nf.close()
def overwrite(filename):
f = open(filename, 'r')
flines = [line.strip() for line in f]
f.close()
f = open(filename, 'w')
for line in flines:
f.write(line)
f.write('\n')
f.close()
choice = raw_input('create file or overwrite file: ')[0].strip().lower()
filename = raw_input('filename: ')
if choice == 'c':
create(filename)
if choice == 'o':
overwrite(filename)
11-12
import time
def timeit(func, *args, **kwargs):
try:
start = time.clock()
retval = func(*args, **kwargs)
end = time.clock()
result = (True, retval, end - start)
except Exception, diag:
result = (False, str(diag))
return result
def test():
funcs = (int, long, float)
vals = (1234, 12.34, '1234', '12.34')
for eachFunc in funcs:
print '_' * 20
for eachVal in vals:
retval = timeit(eachFunc, eachVal)
if retval[0]:
print '%s(%s) cost %f seconds' % (eachFunc.__name__, eachVal, retval[2])
else:
print '%s(%s)=FAILED: ' % (eachFunc.__name__, eachVal), retval[1]
test()
11-13
from fatorial import *
import math, time
def timeit(func, *args, **kwargs):
try:
start = time.clock()
retval = func(*args, **kwargs)
end = time.clock()
result = (True, retval, end - start)
except Exception, diag:
result = (False, str(diag))
return result
def test():
funcs = (factorial1, factorial2, factorial3, math.factorial)
vals = range(521, 531)
for eachFunc in funcs:
print '_' * 40
for eachVal in vals:
retval = timeit(eachFunc, eachVal)
if retval[0]:
print '%s(%s) cost %f seconds' % (eachFunc.__name__, eachVal, retval[2])
else:
print '%s(%s)=FAILED: ' % (eachFunc.__name__, eachVal), retval[1]
test()
11-14
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return (fibonacci(n - 1) + fibonacci(n - 2))
print fibonacci(5)
print fibonacci(6)
print fibonacci(1)
11-15
def func(string, i = 0):
lens = len(string)-1
if i == 0:
print string[i]
func(string, i+1)
elif i == lens:
print string[i]
else:
print string[i-1], string[i+1]
func(string, i+1)
func('string')
11-16
from operator import add, sub, mul, div
from random import randint, choice
ops = {'+': add, '-': sub, '*': mul, '/': div}
MAXTRIES = 2
def doprob():
op = choice('+-*/')
nums = [randint(1, 100) for i in range(2)]
nums.sort(reverse=True)
ans = ops[op](*nums)
pr = '%d %s %d=' % (nums[0], op, nums[1])
oops = 0
while True:
try:
if int(raw_input(pr)) == ans:
print 'correct'
break
if oops == MAXTRIES:
print 'answer\n%s%d' % (pr, ans)
else:
print 'incorrect...try again'
except (KeyboardInterrupt, EOFError, ValueError):
print 'invalid input...try again'
def main():
while True:
doprob()
try:
opt = raw_input('Again? [y]').lower()
if opt and opt[0] == 'n':
break
except (KeyboardInterrupt, EOFError):
break
main()
11-18
person = ['name',['savings',100.00]]
hubby = person[:]
wifey = list(person)
hubby[0] = 'joe'
wifey[0] = 'jane'
def count():
def person_cost(f):
def wrapper(*args,**kargs):
def cost(f,*args,**kargs):
if len(args) != 2:
print 'paras num error'
elif args[0] == 'joe':
hubby[1][1] -= args[1]
print hubby,wifey,person
elif args[0] == 'jane':
wifey[1][1] -= args[1]
print hubby,wifey,person
else:
print 'paras error'
return f(*args,**kargs)
return wrapper
@count
def changehubby(name,money):
print 'change count of %s, minus %f' % (name,money)
@count
def changewifey(name,money):
print 'change count of %s, minus %f' % (name,money)
changehubby('joe',10.0)
changewifey('jane',20.0)