- 编写函数,求1+2+3+…N的和
def sum1(n):
sum2 = 0
for i in range(1, n+1):
sum2 += i
return sum2
print(sum1(5))
- 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
def roll(n):
import random
sum_roll = 0
for i in range(1, n+1):
num = random.randint(1, 6)
print("第%d个骰子的点数是:" %i, num)
sum_roll += num
return sum_roll
print(roll(3))
- 编写一个函数,交换指定字典的key和value。
# 例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def change_dict(dict1):
new_dict = {}
for key in dict1:
new_dict[dict1[key]] = key
print(new_dict)
change_dict(a=1, b=2, c=3) # {1: 'a', 2: 'b', 3: 'c'}
def change_dict(dict1):
for key in dict1.copy():
value = dict1.pop(key)
dict1[value] = key
dict1={'a':1, 'b':2, 'c':3}
change_dict(dict1)
print(dict1)
- 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
# 例如: 传入'12a&bc12d-+' --> 'abcd'
def string_s(str1):
str2 = ''
for item in str1[:]:
if 'A' <= item <= 'Z' or 'a' <= item <= 'z':
str2 += item
return str2
string_s('12a&bc12d-+')
- 写一个函数,求多个数的平均值
def avg(*n):
print(sum(n)/len(n))
avg(1, 5, 5, 8)
- 写一个函数,默认求10的阶乘,也可以求其他数字的阶乘
def jiecheng(n):
result1 = 1
for i in range(1, n+1):
result1 *= i
print(result1)
jiecheng(10)
=====================注意:以下方法不能使用系统提供的方法和函数,全部自己写逻辑==============
- 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
# 例如: 'abc' -> 'Abc' '12asd' --> '12asd'
def capitaliza_ex(str1):
item = str1[0]
str2 = ''
if 'a' <= item <= 'z':
new_item = chr((ord(item)) - 32)
str2 = new_item + str1[1:]
print(str2)
else:
print('首字母不是小写')
capitaliza_ex('a1asdsa')
- 写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
# 例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
# 字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
def endswith_e(str1, end):
length = len(end)
if str1[-length, -1] == end :
return True
return False
print(endswith_e('acvcv', 'cv'))
- 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
# 例如: '1234921' 结果: True
# '23函数' 结果: False
# 'a2390' 结果: False
def n_isdigit(str1):
num = 0
for i in str1:
if not '0' <= i <= '9':
num += 1
if num == 0:
print('True')
else:
print('False')
n_isdigit('12l3456')
- 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
# 例如: 'abH23好rp1' 结果: 'ABH23好RP1'
def upper_a(str1):
str2 = ''
for item in str1:
if 'a' <= item <= 'z':
new_item = chr((ord(item)) - 32)
str2 += new_item
else:
str2 += item
print(str2)
upper_a('asnnAA55')
- 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
# 例如: 原字符:'abc' 宽度: 7 字符:'^' 结果: '^^^^abc'
# 原字符:'你好吗' 宽度: 5 字符:'0' 结果: '00你好吗'
def rjust_func(str1:str,length:int,str2:str):
new_str = ''
new_str = str2 * (length-len(str1)) + str1
return new_str
a = rjust_func('abc',7,'^')
print(a)
- 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
# 例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0] 元素: 1 结果: 0,4,6
# 列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '赵云' 结果: 0,4
#
# 列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '关羽' 结果: -1
def index_func(list1:list,str2):
if str2 in list1:
for index in range(len(list1)):
if str2 == list1[index]:
print(index,end=(','))
print()
else:
print('-1')
index_func([1, 2, 45, 'abc', 1, '你好', 1, 0],1) # 0,4,6,
index_func(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'赵云') # 0,4
index_func(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'关羽') # -1
- 写一个自己的len函数,统计指定序列中元素的个数
# 例如: 序列:[1, 3, 5, 6] 结果: 4
# 序列:(1, 34, 'a', 45, 'bbb') 结果: 5
# 序列:'hello w' 结果: 7
def def_func(a):
count = 0
for item in a:
count += 1
print(count)
def_func([1, 3, 5, 6])
- 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
# 例如: 序列:[-7, -12, -1, -9] 结果: -1
# 序列:'abcdpzasdz' 结果: 'z'
# 序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98
def max_seq(a):
list1 = list(a)
if type(a) == dict:
list1 = list(a.values())
max1 = list1[0]
for item in list1[1:]:
if max1 < item:
max1 = item
return max1
print(max_seq({'小明':90, '张三': 76, '路飞':30, '小花': 98} )) # 98
print(max_seq("abcdpzasdz" ) )# z
print(max_seq([-7, -12, -1, -9])) # -1
- 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
# 例如: 序列: (12, 90, 'abc') 元素: '90' 结果: False
# 序列: [12, 90, 'abc'] 元素: 90 结果: True
def in_func(a,b):
for item in a:
if item == b:
print('Ture')
break
else:
print('False')
in_func([12, 90, 'abc'], 90)
- 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
# 例如: 原字符串: 'how are you? and you?' 旧字符串: 'you' 新字符串:'me' 结果: 'how are me? and me?'
def rep_str(str1 :str, str2 : str, str3 : str, ):
str4 = ""
index = 0
while index < len(str1): # str1 指定的待旧换新字符串
if str1[index : (index + len(str2) )] == str2: # str2旧的字符串
str4 += str3 # str3指定的新字符串
index += len(str2)
else:
str4 += str1[index]
index += 1
return str4
print(rep_str( 'how are you? and you?', 'you', "me" )) # how are me? and me?
- 写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能
def jiao_func(list1:list,list2:list):
for i in list1:
if i in list2:
print(i,end=',')
print()
jiao_func([1,2,3,4],[1,2,3,4,5,6,7,8,9]) # 1,2,3,4,
def bing_func(list1:list,list2:list):
for i in list1:
if i not in list2:
list2.append(i)
return list2
a = bing_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9])
print(a) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def cha_func(list1:list,list2:list):
new_list = []
for i in list1:
if i not in list2:
new_list.append(i)
return new_list
a = cha_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9]) # [10]
print(a)
def bu_func(list1:list,list2:list):
new_list = []
for index1 in list1:
if index1 not in list2:
new_list.append(index1)
for index2 in list2:
if index2 not in list1:
new_list.append(index2)
return new_list
a = bu_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9]) # [10, 5, 6, 7, 8, 9]
print(a)