day11-作业

  1. 写一个生成式能够产生的数据为: 1, 4, 27, 256, 3125,…, 9**9
data = list(n**n for n in range(1, 10))
print(data)
# [1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489]
  1. 写一个生成式能够产生1-10中所有半径是偶数的圆的面积
import math
odd_areas = list(math.pi*r*r for r in range(1, 11) if not r & 1)
print(odd_areas)
# [12.566370614359172, 50.26548245743669, 113.09733552923255, 201.06192982974676, 314.1592653589793]
  1. 写一个生成式交换字典的键和值,产生一个新的字典
dict1 = {'a': 11, 'b': 22, 'c': 33, 'd': '44'}
new_dict = dict((dict1[key], key) for key in dict1)
print(new_dict)
  1. 为函数写一个装饰器,在函数执行之后输出 after
def print_after(fn):
    def inter_func(*args, **kwargs):
        res = fn(*args, **kwargs)
        print('after')
        return res
    return inter_func


@print_after
def swap_key_value(dict0: dict):
    print(dict((dict0[key], key) for key in dict0))
    return dict((dict0[key], key) for key in dict0)


dict1 = {'aa': 1, 'bb': 2, 'cc': 3, 'dd': 4}
print(swap_key_value(dict1))

"""
{1: 'aa', 2: 'bb', 3: 'cc', 4: 'dd'}
after
{1: 'aa', 2: 'bb', 3: 'cc', 4: 'dd'}
"""
  1. 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
import re


def res_add(fn):
    def process(*args, **kwargs):
        res = fn(*args, **kwargs)
        if isinstance(res, int):
            res += 100
        elif isinstance(res, dict):
            for key in res:
                res[key] += 100
        elif isinstance(res, set) or isinstance(res, tuple):
            return 'ERROR'
        elif isinstance(res, str):
            values = re.findall(r'\d+', res)
            # for value in values[:]:
            #     if not value:
            #         values.remove(value)
            k = 0
            for _ in values:
                values[k] = int(values[k]) + 100
                k += 1
            return values
        elif isinstance(res, list):
            k = 0
            for _ in res:
                res[k] += 100
                k += 1
        return res
    return process


@res_add
def func1(num1: int):
    return num1


@res_add
def func2(nums: dict):
    return nums


@res_add
def func3(nums):
    return nums


print(func1(3))
print(func2({'a': 2, 'b': 3, 'c': 4}))
print(func3([3, 4, 5]))
print(func3((1, 2, 3)), func3({1, 2, 3}))
print(func3('sbv1,,23kdnndh6'))
"""
103
{'a': 102, 'b': 103, 'c': 104}
[103, 104, 105]
ERROR ERROR
[101, 123, 106]
"""
  1. 写一个装饰器@tag要求满足如下功能:

    @tag
    def render(text):
        # 执行其他操作
        return text
    
    @tag
    def render2():
        return 'abc'
    
    print(render('Hello'))   # 打印出: <p>Hello</p>
    print(render2())     # 打印出: <p>abc</p>
    
def tag(fn):
    def process(*args, **kwargs):
        return '<p>' + fn(*args, **kwargs) + '</p>'
    return process


@tag
def render(text):
    return text


@tag
def render2():
    return 'abc'


print(render('Hello'))
print(render2())

# <p>Hello</p>
# <p>abc</p>

  1. 写一个装饰器@tag要求满足如下功能(需要使用带参的装饰器,自己先自学正在一下):

    @tag(name='p')
    def render(text):
        # 执行其他操作
        return text
    
    @tag(name='div')
    def render2():
        return 'abc'
    
    print(render('Hello'))   # 打印出: <p>Hello</p>
    print(render2())     # 打印出: <div>abc</div>
    
def tag(name=None):
    def decorator(fn):
        def process(*args, **kwargs):
            return '<' + name + '>' + fn(*args, **kwargs) + '</' + name + '>'
            # return '<%s>%s</%s>'%(name, fn(*args, **kwargs), name)
        return process
    return decorator


@tag(name='p')
def render(text):
    return text


@tag(name='div')
def render2():
    return 'abc'


print(render('Hello'))
print(render2())
  1. 为函数写一个装饰器,根据参数不同做不同操作。
    flag为True,则 让原函数执行后返回值加100,并返回。
    flag为False,则 让原函数执行后返回值减100,并返回。
import re


def operation(fn):
    def process(*args, flag=False, **kwargs):
        res = fn(*args, **kwargs)
        if flag:
            return res + 100
        return res - 100
    return process


@operation
def first_num(str0: str):
    res = re.search('[0-9]+', str0).group()
    return int(res)


print(first_num('abc12dac13'))
print(first_num('abc12dac13', flag=True))

# 方法2
def change_value(is_add):
    def test1(fn):
        def test2(*args, **kwargs):
            if is_add:
                return fn(*args, **kwargs) + 100
            else:
                return fn(*args, **kwargs) - 100
        return test2
    return test1


@change_value(is_add=True)
def func2(x: int, y: int):
    return x*y


print(func2(10, 20))
  1. 写一个斗地主发牌器
import random


def write_placard(color='红桃'):
    def decorator(fn):
        def process(*args, **kwargs):
            res = fn(*args, **kwargs)
            res.append(color+'A')
            for x in range(2, 11):
                res.append(color+str(x))
            res += [color+'J', color+'Q', color+'K']
            return res
        return process
    return decorator


@write_placard()
def get_list1():
    list1 = []
    return list1


@write_placard(color='黑桃')
def get_list2():
    list2 = []
    return list2


@write_placard(color='梅花')
def get_list3():
    list3 = []
    return list3


@write_placard(color='方块')
def get_list4():
    list4 = []
    return list4


placards = get_list1() + get_list2() + get_list3() + get_list4() + ['大王', '小王']
random.shuffle(placards)
card1 = placards.pop(random.randint(0, 53))
card2 = placards.pop(random.randint(0, 52))
card3 = placards.pop(random.randint(0, 51))
landlord = placards[:5] + placards[15:19] + placards[27:31] + placards[39:43]
peasant1 = placards[5:10] + placards[19:23] + placards[31:35] + placards[43:47]
peasant2 = placards[10:15] + placards[23:27] + placards[35:39] + placards[47:51]
print(landlord)
print(peasant1)
print(peasant2)

# 方法2
import random


def new_poker():
    # "创建一副新牌"
    pokers = []
    nums = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    colors = ['♥', '♠', '♣', '◆']

    for num in nums:
        for color in colors:
            pokers.append('%s%s' % (color, num))

    pokers.extend(['小王', '大王'])
    return pokers


def shuffle(pokers):
    # "洗牌"
    random.shuffle(pokers)


def deal(pokers):
    poker_iter = iter(pokers)
    p11, p22, p33, num = [], [], [], 1
    for _ in range(17*3):
        if num == 1:
            p11.append(next(poker_iter))
        elif num == 2:
            p22.append(next(poker_iter))
        elif num == 3:
            p33.append(next(poker_iter))
            num = 0
        num += 1
    return p11, p22, p33, list(poker_iter)


pokers1 = new_poker()
print(pokers1)
shuffle(pokers1)
print(pokers1)
p1, p2, p3, hole = deal(pokers1)
print(p1)
print(p2)
print(p3)
print(hole)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,635评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,628评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,971评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,986评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,006评论 6 394
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,784评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,475评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,364评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,860评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,008评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,152评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,829评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,490评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,035评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,428评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,127评论 2 356

推荐阅读更多精彩内容

  • 写一个生成式能够产生的数据为: 1, 2, 27, 256, 3125,…, 9**9 写一个生成式能够产生1-1...
    丶简单就好丶阅读 178评论 0 1
  • 写一个生成式能够产生的数据为: 1, 4, 27, 256, 3125,…, 9**9 写一个生成式能够产生1-1...
    酒煮灬核弹头阅读 212评论 0 2
  • Git 全局设置: 本地项目上传到git仓库 下载git工具 https://git-scm.com/downlo...
    孙科技阅读 483评论 0 0
  • 1、等,多少的无奈,换来一个难忘,伤感的人,知道自己做什么,无奈的人,知道别人错过了。错,一个人的错,错过好多,好...
    然若一阅读 579评论 1 14
  • “勇于敢则杀,勇于不敢则活。此两者,或利或害。天之所恶,孰知其故?天之道,不正而善胜,不言而善应,不召而自来...
    钱江潮369阅读 275评论 0 1