- 写一个生成式能够产生的数据为: 1, 2, 27, 256, 3125,…, 9**9
nums = (x**x for x in range(1, 10))
- 写一个生成式能够产生1-10中所有半径是偶数的圆的面积
import math
areas = (math.pi*x**2 for x in range(1, 11) if not x & 1)
- 写一个生成式交换字段的键和值,产生一个新的字典
dicts = dict((dict1[key], key) for key in dict1)
- 为函数写一个装饰器,在函数执行之后输出 after
def put(fn):
def test(*args, **kwargs):
fn(*args, **kwargs)
print('after')
return test
- 为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def sums(fn):
def test(*args, **kwargs):
return fn(*args, **kwargs)+100
return test
- 写一个装饰器@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 test(*args, **kwargs):
return '<p>'+fn(*args, **kwargs)+'</p>'
return test
@tag
def render(text):
return text
@tag
def render2():
return 'abc'
print(render('hello'))
print(render2())
- 写一个装饰器@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):
def operation(fn):
def test(*args, **kwargs):
return '<'+name+'>'+fn(*args, **kwargs)+'<'+'/'+name+'>'
return test
return operation
@tag(name='p')
def render(text):
return text
@tag(name='div')
def render2():
return 'abc'
print(render('hello'))
print(render2()
- 为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。
def arguments(flag: bool):
def operation(fn):
def test(*args, **kwargs):
if flag:
return fn(*args, **kwargs)+100
return fn(*args, **kwargs)-100
return test
return operation
@arguments(True)
def func1():
return 100
@arguments(False)
def func2():
return 100
print(func1())
print(func2())
- 写一个斗地主发牌器
import random
# 洗牌
def shuffle():
color_cards = ['\u2665', '\u2660', '\u2666', '\u2663']
normal_cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = ['king', 'joker']
for color in color_cards:
for x in normal_cards:
cards.append(color + x)
random.shuffle(cards)
return cards
# 一个人一次发几张牌
def nums(list1, lists, n):
for _ in range(n):
list1.append(lists.pop(0))
return list1
# 开始发牌
def deal(lists):
player1, player2, player3, landlord = [], [], [], []
for i in range(6):
if i == 0:
n = 2
else:
n = 3
nums(player1, lists, n)
nums(player2, lists, n)
nums(player3, lists, n)
landlord = lists
return [player1, player2, player3, landlord]
for i in deal(shuffle()):
print(i)