- 写一个生成式能够产生的数据为: 1, 2, 27, 256, 3125,…, 9**9
print(list(i**i for i in range(1, 10)))
- 写一个生成式能够产生1-10中所有半径是偶数的圆的面积
print(list(math.pi*i**2 for i in range(1, 10) if not i & 1))
- 写一个生成式交换字段的键和值,产生一个新的字典
wz_dict = {'name': '雾起', 'age': 18}
print(dict((wz_dict[key], key) for key in wz_dict))
- 为函数写一个装饰器,在函数执行之后输出 after
def func1(fn):
def func2(*arge, **kwargs):
fn(*arge, **kwargs)
print('after')
return func2
@func1
def fun3():
print(‘===’)
fun3()
- 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def func1(fn):
def func2(*arge, **kwargs):
num = fn(*arge, **kwargs) + 100
return num
return func2
@func1
def fun3():
return 100
print(fun3())
- 写一个装饰器@tag要求满足如下功能:
def tag(fn):
def render_tag(*args, **kwargs):
new_str ='<p>' + fn(*args, **kwargs) + '</p>'
return new_str
return render_tag
@tag
def render(text):
# 执行其他操作
return text
@tag
def render2():
return 'abc'
print(render('Hello')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
- 写一个装饰器@tag要求满足如下功能(需要使用带参的装饰器,自己先自学正在一下):
def tag(name):
def dt_render(fn):
def wz_render(*args, **kwargs):
new_str = '<{}>'.format(name) + fn(*args, **kwargs) + '</{}>'.format(name)
return new_str
return wz_render
return dt_render
@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>
# render = tag(name='p')(render) # -> dt_render(render) ->wz_render
- 为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。
def dt_flag(fn):
def dt_bool(*args, **kwargs):
if args[0] == 'True':
num = fn(*args, **kwargs) + 100
return num
else:
num = fn(*args, **kwargs) - 100
return num
return dt_bool
@dt_flag
def primary(str):
return 150
print(primary('True'))
print(primary('False'))
- 写一个斗地主发牌器
def deck():
card_king = ['大王', '小王']
card_type = ['♥', '♠', '♣', '◆']
card_value = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']
all_deck = [x + y for x in card_type for y in card_value]
all_deck.extend(card_king)
print('洗牌')
random.shuffle(all_deck)
print('发牌')
down_card = all_deck[:3]
user_card_1 = all_deck[3:20]
user_card_2 = all_deck[20:37]
user_card_3 = all_deck[37:54]
random_number = random.randint(1, 13)
if random_number % 3 == 0:
user_card_1.extend(down_card)
if random_number % 3 == 1:
user_card_2.extend(down_card)
if random_number % 3 == 2:
user_card_3.extend(down_card)
print('底牌:', down_card)
print('牌组为:', user_card_1)
print('牌组为:', user_card_2)
print('牌组为:', user_card_3)
if __name__ == '__main__':
deck()