1.函數將指定的列表逆序
def list_reverse(list):
return list[::-1]
print(list_reverse([1,2,3,4,5,6]))
2.函數提出字符串所有奇數位字符
def get_char(str1):
list2=[]
for x in range(0,len(str1)):
if x%2!=0:
list2.append(str1[x])
print(list2)
get_char('asd2122asd')
3.匿名函數判斷是否閏年
result = lambda x:x%4==0 and (x%100==0 and x%400!=0)
print(result(2008))
4.遞歸打印等腰三角形
def my_print3(n):
if n==1:
print(' '*(5-1),'*')
return None
my_print3(n-1)
print(' '*(5-n),'*'*(2*n-1))
my_print3(3)
my_print3(4)
5.寫函數,判斷列表長度,若長度大于2,存列表前兩個內容并返回
def check_len(list):
list1 = []
if len(list)>2:
list1.append(list[0])
list1.append(list[1])
return list1
print(check_len([1,2,3,4,5]))
6.寫函數求斐波那契數列第10個數
def my_fb(n):
if n==1:
return 0
if n==2:
return 1
return my_fb(n-1)+my_fb(n-2)
print(my_fb(10))
7.寫函數求平均值,最高分
def my_list_max(list):
max = list[0]
for item in list:
if item>max:
max = item
return max
def my_list_avg(list):
sum1 = 0
for item in list:
sum1+=item
return sum1/len(list)
def my_operation(char):
if char =='max':
return my_list_max
if char=='avg':
return my_list_avg
print(my_operation('max')([1,2,3,4,5,6,7]))
print(my_operation('avg')([67,34,86,78,98]))
9.寫函數檢查傳入列表或元組奇數位并返回
def check_list(list):
list1 = []
for x in range(0,len(list)):
if x%2!=0:
list1.append(list[x])
return list1
def check_tuple(tuple1):
list2 =[]
for x in range(0,len(tuple1)):
if x%2!=0:
list2.append(tuple1[x])
tuple2 = tuple(list2)
return tuple2
def choose_operation(char):
if char=='list':
return check_list
if char=='tuple':
return check_tuple
print(choose_operation('list')([7,6,5,4,3,2,1]))
print(choose_operation('tuple')((1,2,3,4,5,6,7)))