一、编写函数包含 位置参数,关键字参数,可变元组参数,可变字典参数
def fun(a, b=20, c=30, *args, **kwargs):
print(a, b, c, args, kwargs)
fun(10, 30, 20, 40, 50, name="Tom", age=20)
二、编写函数验证 全局变量, 局部变量, gloabl与nonlocal关键字使用
v1 = 10
def fun():
global v1
v2 = 20
print(v2)
v1 = 100
def fun1():
nonlocal v2
v2 = 200
return
fun1()
print(v2)
return
print(v1)
fun()
print(v1)
三、编写推导式案例 列表 元组 字典 集合
l = [1, 2, 3, 4, 5, 6]
l1 = [x*2 for x in l]
print(l1)
t1 = (x*3 for x in l)
for e in t1:
print(e)
d1 = {f"key{x}": x for x in l}
print(d1)
s1 = {x**3 for x in l}
print(s1)
四、编写函数求从a,b 相差为c的质数对
def get_primes_pair(a, b, c):
for i in range(a, b + 1):
for j in range(2, i):
if i % j == 0:
break
else:
for x in range(a, i+1):
for y in range(2, x):
if x % y == 0:
break
else:
if i - x == c:
print(i, x, c)
return
get_primes_pair(10, 100, 6)
五、随机10000个位于50-100之间的整数,80%的概率放入列表1,20%的概率放入列表2 求列表1平均数与列表2平均数的差值
def get_difference(start, stop, numbers):
l1 = []
l2 = []
l1_total = 0
l2_total = 0
for i in range(numbers):
value = random.randint(start, stop)
if random.random() <= 0.8:
l1.append(value)
else:
l2.append(value)
for e in l1:
l1_total += e
for e in l2:
l2_total += e
difference = l1_total / len(l1) - l2_total / len(l2)
return difference
print(get_difference(50, 100, 10000))
六、现有一个列表 [1,5,3,2,8,9,4,6]
不适用sort函数 对其进行排序
l = [1, 5, 3, 2, 8, 9, 4, 6]
l1 = []
for i in range(len(l), 0, -1):
l1.append(min(l))
l.remove(min(l))
print(l1)