-
写一个生成式能够产生的数据为: 1, 4, 27, 256, 3125,…, 9**9
gen1 = (n**n for n in range(1, 10))
-
写一个生成式能够产生1-10中所有半径是偶数的圆的面积
import math gen1 = (math.pi * r**2 for r in range(1, 11) if r & 1 == 0)
-
写一个生成式交换字典的键和值,产生一个新的字典
dict1 = {'a': 1, 'b': 2} dict2 = dict((dict1[key], key) for key in dict1)
-
为函数写一个装饰器,在函数执行之后输出 after
def output_after(fn): def test(*args, **kwargs): fn(*args, **kwargs) print('after') return test
-
为函数写一个装饰器,把函数的返回值 +100 然后再返回。
def add_100(fn): def test(*args, **kwargs): return fn(*args, **kwargs) + 100 return test @add_100 def sum(x, y): return x + y print(sum(100, 200))
5. 写一个装饰器@tag要求满足如下功能:
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')) # 打印出: <p>Hello</p>
print(render2()) # 打印出: <p>abc</p>
-
写一个装饰器@tag要求满足如下功能(需要使用带参的装饰器,自己先自学正在一下):
def tag(name): def middle(fn): def test(*args, **kwargs): return '<' + name + '>' + fn(*args, **kwargs) + '</' + name + '>' return test return middle @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>
-
为函数写一个装饰器,根据参数不同做不同操作。
flag为True,则 让原函数执行后返回值加100,并返回。
flag为False,则 让原函数执行后返回值减100,并返回。def tag(flag = True): if flag: def middle(fn): def test(*args, **kwargs): return fn(*args, **kwargs) + 100 return test return middle else: def middle(fn): def test(*args, **kwargs): return fn(*args, **kwargs) - 100 return test return middle @tag(flag=False) def sum(x,y): return x+y print(sum(100, 200))
- 写一个斗地主发牌器
方法一
cards1 = ['大王', '小王']
list5 = ['2', '3', '4', '5', '6', '7,', '8', '9', '10', 'J', 'Q', 'K', 'A']
def fn(char):
for x in list5:
cards1.append(char+x)
fn('♠')
fn('♥')
fn('♦')
fn('♣')
list1 = []
list2 = []
list3 = []
list4 = []
def card(cards):
i = 0
j = 0
for x in set(cards):
i += 1
j += 1
if i >= 52:
list4.append(x)
elif j == 1:
list1.append(x)
elif j == 2:
list2.append(x)
elif j == 3:
j = 0
list3.append(x)
card(cards1)
print(len(list1), list1)
print(len(list2), list2)
print(len(list3), list3)
print(list4)
方法二
import random
list1 = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
cards = ['大王', '小王']
def fn(char: str):
for x in list1:
cards.append(char+x)
fn('♠')
fn('♥')
fn('♦')
fn('♣')
print(cards, len(cards))
def func1():
for x in set(cards):
yield x
gen1 = func1()
x = random.choice(cards)
i = 0
list4 = []
list2 = []
list3 = []
for _ in range(51):
i += 1
if i == 1:
list2.append(next(gen1))
elif i == 2:
list3.append(next(gen1))
elif i == 3:
i = 0
list4.append(next(gen1))
print(list2, len(list2))
print(list3, len(list3))
print(list4, len(list4))
print(x)