1.编写函数,求1 + 2 + 3 +…N的和
def my_sum(n):
"""
求1 + 2 + 3 +…N的和
:param n: int,数字
:return: None
"""
sum1 = 0
for num1 in range(1, n + 1):
sum1 += num1
print('和等于:', sum1)
my_sum(5)
2. 编写一个函数,求多个数中的最大值
list1 = [1, 23, 3, 45, 56, 23, 7238]
def max_value(list1: list):
"""求多个数中的最大值"""
max_value = max(list1)
print(max_value)
max_value(list1)
3.编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
def my_sum1(n: int):
""" 求N个骰子的点数和 """
x = 1
sum1 = 0
while x < n + 1:
import random
random_num = random.randint(1, 6)
x += 1
print('随机数是:', random_num)
sum1 += random_num
print('随机数的和是:', sum1)
my_sum1(5)
4.编写一个函数,交换指定字典的key和value。
例如: dict1 = {'a': 1, 'b': 2, 'c': 3} --> dict1 = {1: 'a', 2: 'b', 3: 'c'}
def my_exchange(**dict1):
"""
交换指定字典的key和value
:param dict1: 一个字典
:return:
"""
dict2 = dict1.copy()
for key in dict2:
dict1[dict1[key]] = key
del dict1[key]
return dict1
print(my_exchange(a=1, b=2, c=3))
老师的方法:
exchange(dict1):
# key = ['a', 'c', 'b']
for key in dict1:
value = dict1[key]
del dict1[key]
dict1[value] = key
dict1 = {'b': 2, 'c': 3, 'a': 1}
exchange(dict1)
print(dict1)
dict2 = {'bab': 290, 'cs': 39, 'a2': 10}
exchange(dict2)
print(dict2)
5. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
例如: 传入
'12a&bc12d-+' --> 'abcd'
def letter1(str1: str):
str2 = ''
for item in str1:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z':
str2 += item
return str2
print(letter1('12312ewre2321de23'))
6.写一个函数,求多个数的平均值
def average_value(*nums):
"""求多个数的平均值"""
sum1 = 0
for num in nums:
# print(num)取出每个数字
sum1 += num # 求所有数字的和
print(sum1 / len([*nums])) # 求平均数
return sum1 # 返回到sum1的值
average_value(1, 2, 4, 4, 5) # 调用函数
7.写一个函数,默认求10的阶乘,也可以求其他数字的阶乘
def factorial(n=10):
product = 1
for num in range(1, n + 1):
product *= num
print(product)
return product
factorial(n=3)
== == == == == == == == == == =注意:以下方法不能使用系统提供的方法和函数,全部自己写逻辑 == == == == == == ==
8.写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如: 'abc' -> 'Abc' '12asd' --> '12asd'
def my_captitalize(str1: str):
"""将指定的字符串的首字母变成大写"""
str2 = ''
if 'a' <= str1[0] <= 'z': # 如果字符串的首字母是小写字母
chr(ord(str1[0]) - 32)
str2 = chr(ord(str1[0]) - 32) + str1[1:]
return str2
else:
return (str1)
print(my_captitalize('24bf23'))
老师的方法:
def yt_capitalize(str1):
first_char = str1[0]
if 'a' <= first_char <= 'z':
first_char = chr(ord(first_char)-32)
return first_char+str1[1:]
print(yt_capitalize('123abchd'))
9.
写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab'
字符串2: 'ab'
函数结果为: True
字符串1: 'abc231ab'
字符串2: 'ab1'
函数结果为: False
def my_endswith(str1: str, str2: str):
if str2[::-1] == str1[-1:-len(str2) - 1:-1]:
return True
else:
return False
print(my_endswith('abc123ab', 'ab'))
# 方法二
def my_endswith(str1: str, str2: str):
if str1[-len(str2):] == str2:
return True
else:
return False
10.
写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
例如: '1234921'
结果: True
'23函数'
结果: False
'a2390'
结果: False
def my_isdigit(str1):
for char in str1:
if not '0' <= char <= '9':
return False
else:
return True
print(my_isdigit('23函数'))
11.
写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
例如: 'abH23好rp1'
结果: 'ABH23好RP1'
def my_upper(str1: str):
"""将指定的字符串的所有母变成大写"""
str2 = ''
for index in range(len(str1)):
if 'a' <= str1[index] <= 'z': # 如果字符串的首字母是小写字母
# chr(ord(str1[index]) - 32)
char = chr(ord(str1[index]) - 32)
str2 += char
else:
str2 += str1[index]
return str2
print(my_upper('a1b2c3'))
12.
写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
例如: 原字符:'abc'
宽度: 7
字符: '^'
结果: '^^^^abc'
原字符: '你好吗'
宽度: 5
字符: '0'
结果: '00你好吗'
def my_rjust(str1:str,str2:str,n:int):
"""
字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
:param str1: 原字符
:param str2: 字符
:param n: 宽度
:return: str3
"""
str3 = str2*(n - len(str1)) + str1
return str3
print(my_rjust('abc','^',7)) #^^^^abc
print(my_rjust('你好吗','0',5)) #00你好吗
13.
写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回 - 1
例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]
元素: 1
结果: 0, 4, 6
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']
元素: '赵云'
结果: 0, 4
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']
元素: '关羽'
结果: -1
def my_index(list1:list,item1):
count = 0
list2 =[]
for index in range(len(list1)):
if list1[index] == item1:
list2.append(index)
count +=1
if count ==0:
print('-1')
else:
return list2
print(my_index([1, 2, 45, 'abc', 1, '你好', 1, 0],item1 = 1))
14.
写一个自己的len函数,统计指定序列中元素的个数
例如: 序列:[1, 3, 5, 6]
结果: 4
序列: (1, 34, 'a', 45, 'bbb')
结果: 5
序列: 'hello w'
结果: 7
def my_len(list1:list):
"""统计指定序列中元素的个数"""
count = 0
list2 = []
for item in list1:
if item != list2:
count += 1
return count
print(my_len([1, 3, 5, 6])) #4
print(my_len((1, 34, 'a', 45, 'bbb'))) #5
15.
写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9]
结果: -1
序列: 'abcdpzasdz'
结果: 'z'
序列: {'小明': 90, '张三': 76, '路飞': 30, '小花': 98}
结果: 98
def my_max(a):
if type(a) != dict:
max1 = a[0]
for item in a:
if item > max1:
max1 = item
return max1
else:
for key in a:
max1 = a[key]
break
for key in a:
if a[key] > max1:
max1 = item
return max1
print(my_max('abcdpzasdz')) #z
老师的方法:def yt_max(seq):
if isinstance(seq, dict):
list1 = list(seq.values())
else:
list1 = list(seq)
max1 = list1[0]
for index in range(1, len(list1)):
item = list1[index]
if item > max1:
max1 = item
return max1
print(yt_max([1, 34, 5]))
print(yt_max(['abs', 'shd', 'wf']))
print(yt_max({'a': 100, 'b': 20, 'c': 105}))
16.
写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
例如: 序列: (12, 90, 'abc')
元素: '90'
结果: False
序列: [12, 90, 'abc']
元素: 90
结果: True
def my_in(n,item1):
for item in n:
if item == item1:
return True
return False
print(my_in((12, 90, 'abc'),'90'))
print(my_in( [12, 90, 'abc'],90))
老师的方法:def yt_in(seq, item):
for x in seq:
if x == item:
return True
return False
print(yt_in([1, 34, 5], 20))
17.
写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
例如: 原字符串: 'how are you? and you?'
旧字符串: 'you'
新字符串: 'me'
结果: 'how are me? and me?'
def my_replace(a,b,c):
str1 =''
count = 0
while count != len(a):
for index in range(count,len(a)):
if a[index:index+len(b)] == b:
str1 += c
count += 3
break
else:
str1 += a[index]
count += 1
break
return str1
print(my_replace('how are you? and you?', 'you','me'))
老师方法:def yt_replace(str1: str, old: str, new: str):
return new.join(str1.split(old))
result = yt_replace('aa yoo how are you? and you?', 'you', 'me')
print(result)
def yt_replace(str1: str, old: str, new: str):
strs = []
temp = ''
len_old = len(old)
index = 0
while index < len(str1):
char = str1[index]
if char != old[0]:
temp += char
else:
temp2 = str1[index: index+len_old]
if temp2 == old:
strs.append(temp+new)
temp = ''
index += len_old
continue
else:
temp += char
index += 1
strs.append(temp)
return ''.join(strs)
print(yt_replace('aa yoo how are you? and you?', 'you', 'me'))
print('aa yoo how are you? and you?'.split('you'))
18.
写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能
def my_jiao(list1,list2):
list3 =[]
for item1 in list1:
for item2 in list2:
if item1 == item2:
list3.append(item1)
return list3
print(my_jiao([1,2,3,'a','b','c'],[1,3,'a','d','e']))
def my_bing(list1,list2):
list3 = []
for item1 in list1:
if item1 not in list3:
list3.append(item1)
for item2 in list2:
if item2 not in list3:
list3.append(item2)
return list3
print(my_bing([1, 2, 3, 'a', 'b', 'c'], [1, 3, 'a', 'd','e']))
print('==================================')
def my_cha(list1,list2):
list3 = []
for item1 in list1: #去除列表1中重复的元素,并将不重复的元素加入到列表3中
if item1 not in list3:
list3.append(item1)
for item2 in list2: #遍历列表2中的元素
if item2 in list3: #判断列表2中的元素是否在列表3中,如果在,就从列表3中移除该元素.
list3.remove(item2)
return list3
print(my_cha([1, 2, 1,3, 'a', 'b', 'c'], [ 3, 'a', 'd', 2,'e']))
print('==================================')
def my_bu(list1,list2):
list3 = []
for item1 in list1: # 去除列表1中重复的元素,同时把列表1中不在列表2中的元素加入列表3中
if item1 not in list2 and item1 not in list3:
list3.append(item1)
for item2 in list2: # 去除列表2中重复的元素,同时把列表2中不在列表1中的元素加入列表3中
if item2 not in list1 and item2 not in list3:
list3.append(item2)
return list3
print(my_bu([1, 2, 1, 3, 'a', 'b', 'c'], [3, 'a', 'd', 2, 'e']))