1,写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}
例如:min_max(2,5,7,8,4) 返回:{‘max’:8,’min’:2}(此题用到max(),min()内置函数)
def min_max(*args):
dic = {}
dic['max'] = max(args)
dic['min'] = min(args)
return dic
2,写函数,传入一个参数n,返回n的阶乘
例如:cal(7) 计算7*6*5*4*3*2*1
def cal(n):
if n == 1:
return 1
return n * cal(n - 1)
3,写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组
例如:[(‘红桃’,2),(‘梅花’,2), …(‘黑桃’,‘A’)]
def playingcard():
card = []
card_nums = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']
card_class = ['红桃', '梅花', '黑桃', '方块']
for i in card_class:
for j in card_nums:
card.append((i, j))
return card
4,有如下函数:
def wrapper():
def inner():
print(666)
wrapper()
你可以任意添加代码,用两种或以上的方法,执行inner函数.
第一种:
def wrapper():
def inner():
print(666)
inner()
wrapper()
第二种:
def wrapper():
def inner():
print(666)
return inner
ret = wrapper()
ret()
5,相关面试题(先从纸上写好答案,然后在运行):
5.1,有函数定义如下:
def calc(a,b,c,d=1,e=2):
return (a+b)*(c-d)+e
请分别写出下列标号代码的输出结果,如果出错请写出Error。
print(calc(1,2,3,4,5))_____2
print(calc(1,2))____Error
print(calc(e=4,c=5,a=2,b=3))___24
print(calc(1,2,3))_____8
print(calc(1,2,3,e=4))____10
print(calc(1,2,3,d=5,4))_____Error
5.2,下面代码打印的结果分别是_list1=[10, 'a'],list2=[123],list3=[10, 'a'].
def extendList(val,list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print('list1=%s'%list1)
print('list2=%s'%list2)
print('list3=%s'%list3)
5.3,写代码完成99乘法表.(升级题)
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
......
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
def nine_nine():
first = 1
two = 1
while 1:
print(first, '*', two, '=', first*two, end=' ')
if first == 9 and two == 9:
break
elif first == two:
print()
first += 1
two = 1
else:
two += 1
明日默写:
1,什么是闭包。
2,迭代器的好处。
3,用while循环模拟for循环(写具体代码)。