求列表全排列
lst = [1,2,3]l1 = [(x,y,z) for x in lst for y in lst for z in lst if x != y if y != z if x != z]print(l1)
给定一个非负整数num,重复的加每一位,直到最后只剩下一位
例如: num = 38,计算过程如下:
3 + 8 =11
1 + 1 = 2
最后输出结果为2
#递归def add(num): if len(str(num)) == 1: return num ret = 0 for i in str(num): ret += int(i) return ret return(add(ret))print(add(8))
#累加器def add(num): ret = 0 for i in str(num): ret += int(i) return retdef cacl(num): ret = num while ret >= 10: ret = add(ret) return retprint(cacl(38))#使用列表解析优化版def add(num): return sum([int(x) for x in str(num)])def cacl(num): ret = num while ret >= 10: ret = add(ret) return retprint(cacl(38))
寻找happy number
happy number值,对一个数字的每一位取平方后相加,对得到的结果反复执行上一步,直到最后只有一位,如果最后结果为1,这个数就为happy number.
例如 19 就是happy number.因为
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
def add(num): ret = 0 for i in str(num): ret += (int(i) ** 2) return retdef happy_number(num): results = {num} ret = num while ret >= 10: ret = add(ret) if ret in results: return False results.add(ret) return ret == 1for i in range(1,10000): if happy_number(i): print('{0} is happy number'.format(i))#使用列表解析优化上版def add(num): return sum([int(x) ** 2 for i in str(num)])def happy_number(num): results = {num} ret = num while ret >= 10: ret = add(ret) if ret in results: return False results.add(ret) return ret == 1for i in range(1,10000): if happy_number(i): print('{0} is happy number'.format(i))
装饰器
写一个带一个default_user 参数的装饰器,此装饰器检查传入函数的关键字参数,如果没有名为user的参数,使用default_user 作为user 参数传递给函数.
例如:
@inject_user(default_user=comyn)
def do_something(*args,**kwargs):
print(kwargs['user'])
调用do_something() 时能输入comyn
from functools import wrapsdef inject_user(default_user): def func(fn): @wraps(fn) def deco(*args, **kwargs): if 'user' not in kwargs.keys(): kwargs['user'] = default_user return fn(*args, **kwargs) return deco return func @inject_user(default_user='comyn')def do_somethings(*args, **kwargs): print(kwargs['user']) do_somethings()
列表匹配
写一个find函数,传入两个列表,其中origin和iterms, items具有默认值[3, 4].查找iterms中每个元素在origin中的所有位置.返回值为字典,key是iterms中的元素,value是位置的元组.
例如:
find([2, 3, 5, 3, 4, 2, 7, 4]) 返回{3:(1, 3), 4:(4, 7)}
def find(origin,items=[3, 4]): fin = dict() for x in iter(items): lst = list() for k, v in enumerate(origin): if x == v: lst.append(k) fin[x] = tuple(lst) return finfind([2, 3, 5, 3, 4, 2, 7, 4])#使用列表解析优化def find(origin,items=[3, 4]): fin = dict() for x in items: lst = list() [lst.append(k) for k, v in enumerate(origin) if x == v] fin[x] = tuple(lst) return finfind([2, 3, 5, 3, 4, 2, 7, 4])