@classmethod
def how_many(cls):
return cls.__count
def __init__(self, name):
self.name = name
Person.__count += 1
def how_many(cls):
return cls.__count
def __init__(self, name):
self.name = name
Person.__count += 1
2015-12-29
def get_grade(self):
return 'A' if self.score >= 80 else ('B' if self.score >= 60 else 'C')
return 'A' if self.score >= 80 else ('B' if self.score >= 60 else 'C')
2015-12-29
import time
def performance(f):
def fn(*args, **kw):
start = time.time()
res = f(*args, **kw)
end = time.time()
print 'call %s() in : %fs' % (f.__name__,end - start)
return res
return fn
def performance(f):
def fn(*args, **kw):
start = time.time()
res = f(*args, **kw)
end = time.time()
print 'call %s() in : %fs' % (f.__name__,end - start)
return res
return fn
2015-12-29
def cmp_ignore_case(s1, s2):
return -1 if s1.lower() < s2.lower() else 1
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
return -1 if s1.lower() < s2.lower() else 1
print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
2015-12-29
def calc_prod(lst):
def sum_list():
return reduce((lambda x, y:x * y),lst)
return sum_list
f = calc_prod([1, 2, 3, 4])
print f()
def sum_list():
return reduce((lambda x, y:x * y),lst)
return sum_list
f = calc_prod([1, 2, 3, 4])
print f()
2015-12-29
考虑到前n个字母一样,需要继续往后比较以排序的情况:
def cmp_ignore_case(s1, s2):
for i in range(len(s1)) if len(s1) <= len(s2) else range(len(s2)):
if(s1[i].upper() == s2[i].upper()):
continue
if(s1[i].upper() > s2[i].upper()):
return 1
else:
return -1
def cmp_ignore_case(s1, s2):
for i in range(len(s1)) if len(s1) <= len(s2) else range(len(s2)):
if(s1[i].upper() == s2[i].upper()):
continue
if(s1[i].upper() > s2[i].upper()):
return 1
else:
return -1
2015-12-29
在循环里是没办法用闭包的因为参数是改变的,但如果想用可以把要实现功能的函数再封装一层,每次循环只是调用一次内部函数,这样既可以循环调用,又是闭包不受循环变量的影响
2015-12-28
import math
def is_sqr(x):
return math.sqrt(x)- int(math.sqrt(x)) == 0
print filter(is_sqr, range(1, 101))
def is_sqr(x):
return math.sqrt(x)- int(math.sqrt(x)) == 0
print filter(is_sqr, range(1, 101))
2015-12-28