0.写一个匿名函数,判断指定的年是否是闰年
答案:
leap_year = lambda year :(year % 4 ==0 and year % 100 !=0) or year % 400 ==0
print(leap_year(1900))
print(leap_year(2004))
print(leap_year(2000))
1.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使 表自带的逆序函数)
答案:
def revers_list(a:list):
aa = [ ]
index = len(a)-1
while 0 <= index:
aa.append(a[index])
index -=1
return aa
print(revers_list([1,2,3,"c","b","a"]))
def revers(list1:list):
length = len(list1)
for index in range(length//2):
list1[index],list1[length-1-index] = list1[length-1-index],list1[index]
list1 = [1,2,3,4]
revers(list1)
print(list1)
2.写一个函数,提取出字符串中所有奇数位上的字符
答案:
def odd_number(str1:str):
enpty_str = ""
str1_len = len(str1)
for i in range(1,str1_len+1,2):
enpty_str += str1[i-1]
return enpty_str
print(odd_number("1acds525796"))
3.写一个函数,统计指定列表中指定元素的个数(不用列表自带的count方法)
答案:
def count_element(list1:list,element:str):
count = 0
for item in list1:
if str(item) == element:
count += 1
return count
print("a元素在列表中出现了:",count_element(["a",2,"d","a",6,"w","r","t","y",2,"a","a","a"],"a"))
4.写一个函数,获取指定列表中指定元素的下标(如果指定元素有多个,将每个元素的下标都返回)
答案:
例如: 列表是:[1, 3, 4, 1] ,元素是1, 返回:0,3
答案:
def back_elemt_index(list2:list,elemt:str):
a = [ ]
index_item = 0
while index_item <= len(list2)-1:
if list2[index_item] == elemt:
a.append(index_item)
index_item += 1
return a
print("返回值",back_elemt_index([ 2,"a", "d", "a", 6, "w", "r", "t", "y", 2, "a", "a", "a"],"a"))
5.写一个函数,能够将一个字典中的键值对添加到另外一个字典中(不使用字典自带的update方法)
答案:
def updata_dict2_to_dict1(dict1:dict,dict2:dict):
for key in dict2:
dict1[key] = dict2[key]
return dict1
print(updata_dict2_to_dict1({"name":"lorry","age":23},{"hobby":{"money","girls"},"sex":"man"}))
6.写一个函数,能够将指定字符串中的所有的小写字母转换成大写字母;所有的大写字母转换成小写字母(不能使用字符串相关方法)
答案:
def big_small_exchange(str3):
str4 = ""
for item in str3:
if "a" <= item <= "z":
a = ord(str(item))
b = a-32
new_item =chr(b)
str4 += str(new_item)
elif "A" <= item <= "Z":
a = ord(str(item))
b = a + 32
new_item = chr(b)
str4 += str(new_item)
else:
str4 += str(item)
return str4
print(big_small_exchange("Aas--/+dA"))
7.写一个函数,能够将指定字符串中的指定子串替换成指定的其他子串(不能使用字符串的replace方法)
例如: func1('abcdaxyz', 'a', '') - 返回: '\bcd\xyz'
答案:
def exchange_element_to_other(str1:str,element1:str,element2:str):
index = 0
new_str = ""
while index <= len(str1)-1:
if str1[index] ==element1:
new_str += element2
else:
new_str += str1[index]
index += 1
return new_str
print(exchange_element_to_other("dasddaagha","a","**"))
8.实现一个输入自己的items方法,可以将自定的字典转换成列表。列表中的元素是小的列表,里面是key和value (不能使用字典的items方法)
例如:{'a':1, 'b':2} 转换成 [['a', 1], ['b', 2]
答案:
def dict_to_list(dict1:dict):
new_list = []
for key in dict1:
a = []
a.append(key)
a.append(dict1[key])
new_list.append(a)
return new_list
print(dict_to_list({"name":"lorry","age":23,"hobby":"girls","sex":"man"}))