1.写⼀个函数将⼀个指定的列表中的元素逆序(例如[1, 2, 3] -> [3, 2, 1])
(注意:不要使⽤列表⾃带的逆序函数)
def opp(list1):
new_list = []
# 逆序遍历列表,结果存入新列表
for item in list1[::-1]:
new_list.append(item)
return new_list
list1 = [1,'3',6,9,8]
print(list1,opp(list1))
输出结果:
[1, '3', 6, 9, 8] [8, 9, 6, '3', 1]
2.写⼀个函数,提取出字符串中所有奇数位上的字符
def index_odd(str1):
str2 = ""
# 遍历字符串,步进为2,得到奇数位上的字符
for index in range(0,len(str1), 2):
str2 += str1[index]
return str2
str1 = 'a5s6d5f8g7'
print(str1, index_odd(str1))
输出结果:
a5s6d5f8g7 asdfg
3.写⼀个匿名函数,判断指定的年是否是闰年
a =lambda n: ('%d是闰年' % n) if ((n%100 !=0 and n%4==0) or (n%100==0 and n%400==0)) else ('%d不是闰年' % n)
year = int(input('请输入年份:'))
print(a(year))
输出结果:
请输入年份:2004
2004是闰年
4.使⽤递归打印:
n = 3的时候
@
@@@
@@@@@
n = 4的时候:
@
@@@
@@@@@
@@@@@@@
def pri(n, m=0):
img = "@"
if n == 0:
return
# f(n) = f(n-1)+'@'*2*(n-1)
pri(n-1, m+1)
print(' '*m, end='')
print((img+'@'*(n-1)*2))
pri(4)
输出结果:
@
@@@
@@@@@
@@@@@@@
5.写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def check(list1):
list2 = []
i = 0
if len(list1) > 2:
for item in list1:
list2.append(item)
i += 1
if i == 2:
break
return list2
list1 = ['a', 5, 'c', 9]
print(list1,check(list1))
输出结果:
['a', 5, 'c', 9] ['a', 5]
# 6.写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者。
# 1 1 2 3 5 8 13 21 34 55
def feibo(n=10):
if n == 1 or n == 2:
return 2
"""
fn = fn-1 + fn-2
"""
return feibo(n-1) + feibo(n-2)
print(feibo())
输出结果:
55
7.写一个函数,获取列表中的成绩的平均值,和最高分
def get_num(list1):
sum1 = 0
ave = 0
max = list1[0]
for item in list1:
sum1 += item
if max < item:
max = item
ave = sum1/len(list1)
return ave,max
scord = [65,89,12,65,23,86,96]
print(get_num(scord))
输出结果:
(62.285714285714285, 96)
8.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调⽤用者
def new(xulie):
a = []
for index in range(0, len(xulie), 2):
a.append(xulie[index])
return a
a = [1,2,3,6,5,4,8]
b = (6,9,8,5,7,8,415,8)
print(new(a))
print(new(b))
输出结果:
[1, 3, 5, 8]
[6, 8, 7, 415]
···
网友评论