002_exercises

[TOC]

一.全排列

求列表[1, 2, 3]的全排列
参考答案:
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

lst = [1, 2, 3]
[(x, y, z)  for x in lst for y in lst for z in lst if x != y if x !=z if y != z]
import itertools

lst = [1, 2, 3]
ret = []

for x in itertools.permutations(lst,len(lst)):
            ret.append(x)
print(ret)
import itertools

lst = [1, 2, 3]
ret = []

for i in range(1,len(lst) + 1):
        for x in itertools.permutations(lst,i):
            ret.append(x)
print(ret)

二.重复加,直到最后剩下个位数,求出这个个位数

给定一个非负整数num,重复的加每一位,直到最后只剩下一位;
例如: num = 38,计算过程如下:
3 + 8 =11
1 + 1 = 2
最后输出结果为2
方法一:

from functools import reduce

inputnum = input("please input a num")
while True:
    if len(inputnum) == 1:
        print(inputnum)
        break
    else:
        ret = reduce(lambda x, y:int(x) + int(y), iter(inputnum))
        inputnum = str(ret)

方法二:

def add(num):
    if len(str(num)) == 1:
        return num
    ret = 0
    for i in str(num):
        ret += int(i)
    return add(ret)
print(add(38))

方法三:

def add(num):
    ret = 0
    for i in str(num):
        ret += int(i)
    return ret

def cacl(num):
    ret = num
    while ret >= 10:
        ret = add(ret)
    return ret
print(cacl(38))

方法四:

def add(num):
    return

三.寻找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 ret

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 == 1

for i in range(1,10000):
    if happy_number(i):
        print('{0} is happy number'.format(i))
def add(num):
    return sum([(int(i) ** 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 == 1

for 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 wraps
def 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 fin

find([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 fin

find([2, 3, 5, 3, 4, 2, 7, 4])

你可能感兴趣的:(002_exercises)