# 函数相关练习题

```1,写函数,接收一个参数(此参数类型必须是可迭代对象),将可迭代对象的每个元素以’_’相连接,形成新的字符串,并返回.

1)
def func(lst):
l1 = []
for i in lst:
l1.append(str(i))
return ‘_‘.join(l1)

print(func([1,‘天王‘,‘刘德华‘]))

2)
def func(lst):
s = ‘‘
for i in lst:
s=s+str(i)+‘_‘
return s.strip(‘_‘)

print(func([1,‘天王‘,‘刘德华‘]))```
```2,写函数，传入n个数，返回字典{‘max’:最大值,’min’:最小值}

1)
def func(*args):
the_max = args[0]
the_min = args[0]
for i in args:
if i > the_max:
the_max = i
elif i < the_min:
the_min = i
return {‘max‘: the_max, ‘min‘: the_min}

ret=func(1,3,23,4,8,34,78)
print(ret)

2)
def func(*args):
return {‘max‘:max(args),‘min‘:min(args)}
ret=func(1,3,23,4,8,34,78)
print(ret)```
```3,写函数，传入一个参数n，返回n的阶乘

1)
def cal(n):
sum = 1
for i in range(n, 0, -1):
sum = sum * i
return sum
print(cal(3))

2)
def cal(n):
sum = 1
while n > 0:
sum =sum * n
n -= 1
return sum
print(cal(3))```
```4,写函数，返回一个扑克牌列表，里面有52项，每一项是一个元组

def func():
result=[]
lst1 = [‘红心‘,‘草花‘,‘黑桃‘,‘方片‘]
lst2 = [2,3,4,5,6,7,8,9,10,‘J‘,‘Q‘,‘K‘,‘A‘]
for i in lst1:
for j in lst2:
result.append((i,j))   #小括号是本题要重点注意的
return result
print(func())```
```5,#写代码完成99乘法表.
for x in range(1,10):
for y in range(1,x+1):
r=x*y
print("%s * %s= %s " % (x,y,r)," ",end="")
print(end="\n")```
```5, 一道公司的面试题
1)
def calc(a,b,c,d=1,e=2):
return (a+b)*(c-d)+e
print(calc(1,2,3,4,5))   #2
print(calc(1,2))  #err
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))  #eerr

2)
def extendList(val, list=[]):  # 默认值如果是可变的数据类型. 每次使用的时候都是同一个
#     print(id(list))
#     list.append(val)
#     return list
#
#
# list1 = extendList(10)
# list2 = extendList(123, [])
# list3 = extendList(‘a‘)
#
# print(‘list1=%s‘ % list1)   #list1=[10, ‘a‘]
# print(‘list2=%s‘ % list2)   #list2=[123]
# print(‘list3=%s‘ % list3)   #list3=[10,‘a‘]```

(0)
(0)

0条