- 写⼀一个函数将⼀一个指定的列列表中的元素逆序(例例如[1, 2, 3]-> [3, 2, 1])(注意:不不要使⽤用列列表⾃自带的逆序函数)
def reverse(list1):
n = len(list1) # 找出list1 内有多少个值,并作为取值下标
list2 = [] # 声明一个空列表,用于储存变更后的值
while True:
list2.append(list1[n-1]) # 取出list1 中的值放入list2 中
n -= 1 # 每次取值后list1 的下标向前进一位
if n == 0:
break # 取值完毕结束循环
print(list2)
reverse([1, 2, 3])
[3, 2, 1]
Process finished with exit code 0
- 写⼀一个函数,提取出字符串串中所有奇数位上的字符
def get_odd(str1):
n = len(str1) # 找出str1 内有多少个值
str2 = '' # 声明一个空字符串,用于储存提取后的值
x = 0 # 声明x 做为取值下标,初始为第一个
while True:
str2 += str1[x]
x += 2 # 跳过偶数位
if x >= n: # 限制取值下标范围
break
print(str2)
get_odd('abcdef')
get_odd('abcdefg')
ace
aceg
Process finished with exit code 0
- 写⼀一个匿匿名函数,判断指定的年年是否是闰年年
def judge_leap_year(year):
judge_leap_year = lambda year: year % 4 # 判定是否是润年的方法
if judge_leap_year(year):
print('不是闰年')
else:
print('是闰年')
judge_leap_year(2007)
judge_leap_year(2008)
不是闰年
是闰年
Process finished with exit code 0
- 使⽤用递归打印:
n = 3的时候
@
@@@
@@@@@
n = 4的时候:
@
@@@
@@@@@
@@@@@@@
i = 0
def star(n):
global i
m = n
m += i
if n == 1:
str1 = '@'
print(str1.center(m + m - 1), ' ')
i = 0
return
i += 1
star(n-1)
str2 = '@' * ( n + n - 1)
print(str2.center(m + m - 1), ' ')
star(3)
star(4)
@
@@@
@@@@@
@
@@@
@@@@@
@@@@@@@
Process finished with exit code 0
- 写函数,检查传⼊入列列表的⻓长度,如果⼤大于2,那么仅保留留前两个⻓长度的内容,并将新内容返回给调⽤用者。
def check_list(list1):
n = len(list1)
if n > 2:
print(list1[0:2])
else:
return '长度小于2'
check_list([1, 2, 3])
[1, 2]
Process finished with exit code 0
- 写函数,利利⽤用递归获取斐波那契数列列中的第 10 个数,并将该值返回给调⽤用者。
def Fibonacci_sequence(n):
n1 = 1
n2 = 1
time = 0
if n < 3:
print(n1)
while True:
n3 = n1 + n2
n1 = n2
n2 = n3
time += 1
if time == n - 2:
print(n3)
break
Fibonacci_sequence(10)
55
Process finished with exit code 0
- 写⼀一个函数,获取列列表中的成绩的平均值,和最⾼高分
def average_max(list1):
sum1 = 0
time = 0
for item in list1:
sum1 += item
time += 1
print(sum1 / time)
print(max(list1))
average_max([1, 3, 9, 7])
5.0
9
Process finished with exit code 0
- 写函数,检查获取传⼊入列列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列列表返回给调⽤用者
def check1(list_tumple):
new = []
for item in list_tumple[::2]:
new.append(item)
print(new)
check1([1, 2, 3, 4, 5])
check1((1, 2, 3, 4, 5))
[1, 3, 5]
[1, 3, 5]
Process finished with exit code 0
网友评论