1.写一个函数,将指定的列表元素逆序输出
(例如[1,2,3]-->[3,2,1])
def inverted_print(list1):
list2 = []
for item in list1:
list2.insert(0, item)
return list2
list1 = [1, 2, 3]
print(inverted_print(list1))
>>>[3, 2, 1]
2.写个函数,提取出字符串上所有奇数位的字符
def odd_char(str1):
return str1[::2]
str1 = '123456asdf'
print(odd_char(str1))
>>>135ad
3.写个匿名函数,判断指定的年是否是闰年
judge = lambda x:x % 4 == 0 and x % 100 != 0
if judge(2004):
print('是闰年')
else:
print('不是闰年')
>>>是闰年
4.使用递归打印图形(等腰三角形)
"""
n = 3
@
@@@
@@@@@
"""
blank = 1
def gra_print(n):
global blank
blank += 1
if n == 1:
print(' '*(blank - n) + '@')
return
gra_print(n - 1)
print(' '*(blank - n ) + '@'*(2 * n - 1))
gra_print(3)
>>>
@
@@@
@@@@@
5.写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def retain_two(list1):
list2 = []
if len(list1) >= 2:
list2.append(list1[0])
list2.append(list1[1])
return list2
print(retain_two([1, 2, 3]))
>>>[1, 2]
6.写函数,利递归获取斐波那契数列中的第 10 个数,并将该值返回给调调者。
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
print(fib(10))
>>>55
7.写个函数,获取列表中的成绩的平均值,和最高分
def get_avg_max(list1):
sum1 = 0
max1 = list1[0]
avg1 = list1[0]
for item in list1:
sum1 += item
if max1 < item:
max1 = item
avg1 = sum1 / len(list1)
return avg1,max1
print(get_avg_max([66, 77, 88]))
>>>(77.0, 88)
8.检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调
def odd_index(list1):
list2 = list1[1::2]
return list2
print(odd_index([1, 2, 3, 4, 5, 6, 7]))
print(odd_index((1, 2, 3, 4, 5, 6, 7)))