1.写一个函数将一个指定的列表中的元素逆序(如[1, 2, 3] -> [3, 2, 1])(注意:不要使列表自带的逆序函数)
def reverse_order(list1):
right = len(list1) - 1
left = 0
if len(list1) % 2:
while left != right:
list1[left], list1[right] = list1[right], list1[left]
left += 1
right -= 1
else:
while left != right and left <= len(list1) // 2 - 1 and right >= len(list1) // 2:
list1[left], list1[right] = list1[right], list1[left]
left += 1
right -= 1
list2 = [1, 2, 3, 4, 5, 9]
print('原列表:', list2)
reverse_order(list2)
print('逆序后:', list2)

2.写一个函数,提取出字符串中所有奇数位上的字符
def get_factor(str1:str):
str2 = ''
for index in range(len(str1)):
if index % 2:
str2 += str1[index]
else:
continue
return str2
str3 = 'afjdfk45fd545f6'
print('old:', str3)
print('new:', get_factor(str3))

3.写一个匿名函数,判断指定的年是否是闰年
year%4==0 and year%100!=0 or year%400==0
years = int(input('请输入年份:'))
if (lambda year : year % 4 == 0 and year % 100 != 0 or year % 400 == 0)(years):
print('%d 是闰年' % years)
else:
print('%d 不是闰年'% years)


4.使用递归打印:
"""
n = 3的时候
@
@ @ @
@ @ @ @ @
n = 4的时候:
@
@ @ @
@ @ @ @ @
@ @ @ @ @ @ @
"""
def print_star(n):
row = 0
if n == 1:
return 1
print(' ' * print_star(),'*' * print_star(2*n-1))
num = int(input('请输入一个正整数:'))
row = 1
while row <= num:
print(' ' * (num - row),'*' * (row + (row - 1)))
row += 1
print_star(3)
5.写函数, 利用递归获取斐波那契数列中的第10个数,并将该值返回给调用者。
def qf_feibo(n):
while n < 2:
return n
while n >= 2:
return qf_feibo(n - 1) + qf_feibo(n - 2)
num = int(input('请输入需要求第几个数:'))
print(qf_feibo(num))

6.写一个函数,获取列表中的成绩的平均值,和最高分
def get_score_average(list1):
sum1 = 0
max1 = list1[0]
for score in list1:
sum1 += score
if score >= max1:
max1 = score
return sum1, max1
list2 = [87, 80, 90, 62.5, 75.5]
scores = get_score_average(list2)
print('总分:%.2f 最高分:%.2f' % (scores[0], scores[1]))

7.写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
def get_factor(list1):
list2 = []
for index in range(len(list1)):
if index % 2:
list2.append(list1[index])
else:
continue
return list2
list3 = [87, 80, 90, 62.5, 75.5]
print(list3)
print(get_factor(list3))

8.实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)
如:yt_update(字典1, 字典2)
def qf_update(dict1:dict, dict2:dict):
for key1 in dict1.copy():
for key2 in dict2.copy():
if key1 == key2:
dict1[key1] = dict2[key2]
else:
dict1[key2] = dict2[key2]
dict3 = {'a': 1, 'b': 2}
dict4 = {'hh': 100, 'a': 200, 4: 400}
print('old:', dict3)
print('old:',dict4)
qf_update(dict3, dict4)
print('new:',dict3)

9.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
如:yt_items(字典)
例如:{'a': 1, 'b': 2, 'c': 3} - --> [('a', 1), ('b', 2), ('c', 3)]
def qf_item(dict1):
list1 = []
for key in dict1.copy():
list1.append((key, dict1[key]))
return list1
dict4 = {'hh': 100, 'a': 200, 4: 400}
print('old:', dict4)
print('new:', qf_item(dict4))

网友评论