- 編寫函數(shù)渠欺,求1+2+3+…N的和
def sum1(n):
sum2 = 0
for i in range(1, n+1):
sum2 += i
return sum2
print(sum1(5))
- 編寫一個(gè)函數(shù)椎眯,實(shí)現(xiàn)搖骰子的功能,打印N個(gè)骰子的點(diǎn)數(shù)和
def roll(n):
import random
sum_roll = 0
for i in range(1, n+1):
num = random.randint(1, 6)
print("第%d個(gè)骰子的點(diǎn)數(shù)是:" %i, num)
sum_roll += num
return sum_roll
print(roll(3))
- 編寫一個(gè)函數(shù)捐名,交換指定字典的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)
- 編寫一個(gè)函數(shù),提取指定字符串中所有的字母淆两,然后拼接在一起產(chǎn)生一個(gè)新的字符串
# 例如: 傳入'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-+')
- 寫一個(gè)函數(shù)拂酣,求多個(gè)數(shù)的平均值
def avg(*n):
print(sum(n)/len(n))
avg(1, 5, 5, 8)
- 寫一個(gè)函數(shù),默認(rèn)求10的階乘剑勾,也可以求其他數(shù)字的階乘
def jiecheng(n):
result1 = 1
for i in range(1, n+1):
result1 *= i
print(result1)
jiecheng(10)
=====================注意:以下方法不能使用系統(tǒng)提供的方法和函數(shù)赵颅,全部自己寫邏輯==============
- 寫一個(gè)自己的capitalize函數(shù)饺谬,能夠?qū)⒅付ㄗ址氖鬃帜缸兂纱髮懽帜?/li>
# 例如: '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')
- 寫一個(gè)自己的endswith函數(shù),判斷一個(gè)字符串是否已指定的字符串結(jié)束
# 例如: 字符串1:'abc231ab' 字符串2:'ab' 函數(shù)結(jié)果為: True
# 字符串1:'abc231ab' 字符串2:'ab1' 函數(shù)結(jié)果為: False
def endswith_e(str1, end):
length = len(end)
if str1[-length, -1] == end :
return True
return False
print(endswith_e('acvcv', 'cv'))
- 寫一個(gè)自己的isdigit函數(shù)族展,判斷一個(gè)字符串是否是純數(shù)字字符串
# 例如: '1234921' 結(jié)果: True
# '23函數(shù)' 結(jié)果: False
# 'a2390' 結(jié)果: 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')
- 寫一個(gè)自己的upper函數(shù)仪缸,將一個(gè)字符串中所有的小寫字母變成大寫字母
# 例如: 'abH23好rp1' 結(jié)果: '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')
- 寫一個(gè)自己的rjust函數(shù)列肢,創(chuàng)建一個(gè)字符串的長(zhǎng)度是指定長(zhǎng)度例书,原字符串在新字符串中右對(duì)齊刻炒,剩下的部分用指定的字符填充
# 例如: 原字符:'abc' 寬度: 7 字符:'^' 結(jié)果: '^^^^abc'
# 原字符:'你好嗎' 寬度: 5 字符:'0' 結(jié)果: '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)
- 寫一個(gè)自己的index函數(shù),統(tǒng)計(jì)指定列表中指定元素的所有下標(biāo)树瞭,如果列表中沒有指定元素返回-1
# 例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0] 元素: 1 結(jié)果: 0,4,6
# 列表: ['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)'] 元素: '趙云' 結(jié)果: 0,4
#
# 列表: ['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)'] 元素: '關(guān)羽' 結(jié)果: -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(['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)'],'趙云') # 0,4
index_func(['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)'],'關(guān)羽') # -1
- 寫一個(gè)自己的len函數(shù)晒喷,統(tǒng)計(jì)指定序列中元素的個(gè)數(shù)
# 例如: 序列:[1, 3, 5, 6] 結(jié)果: 4
# 序列:(1, 34, 'a', 45, 'bbb') 結(jié)果: 5
# 序列:'hello w' 結(jié)果: 7
def def_func(a):
count = 0
for item in a:
count += 1
print(count)
def_func([1, 3, 5, 6])
- 寫一個(gè)自己的max函數(shù)访敌,獲取指定序列中元素的最大值。如果序列是字典爷抓,取字典值的最大值
# 例如: 序列:[-7, -12, -1, -9] 結(jié)果: -1
# 序列:'abcdpzasdz' 結(jié)果: 'z'
# 序列:{'小明':90, '張三': 76, '路飛':30, '小花': 98} 結(jié)果: 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
- 寫一個(gè)函數(shù)實(shí)現(xiàn)自己in操作蓝撇,判斷指定序列中,指定的元素是否存在
# 例如: 序列: (12, 90, 'abc') 元素: '90' 結(jié)果: False
# 序列: [12, 90, 'abc'] 元素: 90 結(jié)果: 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)
- 寫一個(gè)自己的replace函數(shù)虽抄,將指定字符串中指定的舊字符串轉(zhuǎn)換成指定的新字符串
# 例如: 原字符串: 'how are you? and you?' 舊字符串: 'you' 新字符串:'me' 結(jié)果: '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?
- 寫四個(gè)函數(shù)独柑,分別實(shí)現(xiàn)求兩個(gè)列表的交集群嗤、并集、差集狂秘、補(bǔ)集的功能
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)