# 1.編寫函數(shù)嘱函,求1+2+3+…N的和
```python
def yt_sum1(n):
? ? return sum(range(1,n+1))
print(yt_sum1(10))
# 2.編寫一個函數(shù)埂蕊,求多個數(shù)中的最大值
def yt_max(*nums):
? ? max1= nums[0]
for numin nums[1:]:
? ? ? ? if num> max1:
? ? ? ? ? ? max1= num
return max1
print(yt_max(19,992,-93,0))
# 4. 編寫一個函數(shù),交換指定字典的key和value
dict1= {'a': 1,'b': 2}# {1: 'a', 2: 'b'}
def exchange_key_value(dictx: dict):
? ? # 注意: 遍歷刪除和增加蓄氧,遍歷對象應(yīng)該原來沒有進行修改的原容器的值。
? ? for keyin dictx.copy():
? ? ? ? value= dictx[key]
print(key)
dictx.pop(key)
dictx[value]= key
exchange_key_value(dict1)
print(dict1)
# 9.寫一個自己的endswith函數(shù)撇寞,判斷一個字符串是否已指定的字符串結(jié)束
# 例如: 字符串1:'abc231ab' 字符串2:'ab' 函數(shù)結(jié)果為: True
# 字符串1:'abc231ab' 字符串2:'ab1' 函數(shù)結(jié)果為: False
def endswith(str1: str,str2: str):
? ? len2= len(str2)
end= str1[-len2:]
return end== str2
if endswith('text.c','.py'):
? ? print('是python源文件')
else:
? ? print('不是python源文件')
# 10.寫一個自己的isdigit函數(shù),判斷一個字符串是否是純數(shù)字字符串
# 例如: '1234921' 結(jié)果: True
# '23函數(shù)' 結(jié)果: False
# 'a2390' 結(jié)果: False
def isdigit(str1: str):
? ? for charin str1:
? ? ? ? if not '0' <= char<= '9':
? ? ? ? ? ? return False
return True
print(isdigit('2a333'))
# 12.寫一個自己的rjust函數(shù)蔑担,創(chuàng)建一個字符串的長度是指定長度,原字符串在新字符串中右對齊鸟缕,剩下的部分用指定的字符填充
# 例如: 原字符:'abc'? 寬度: 7? 字符:'^'? ? 結(jié)果: '^^^^abc'
# 原字符:'你好嗎'? 寬度: 5? 字符:'0'? ? 結(jié)果: '00你好嗎'
def rjust(str1: str,width: int,char: str):
? ? count= width - len(str1)
return count*char+str1
print(rjust('abc',7,'^'))
print(rjust('你好嗎',5,'0'))
# 13.寫一個自己的index函數(shù)排抬,統(tǒng)計指定列表中指定元素的所有下標懂从,如果列表中沒有指定元素返回-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(list1: list,item):
? ? if item not in list1:
? ? ? ? return -1
? ? indexs= []
for xin range(len(list1)):
? ? ? ? if list1[x]== item:
? ? ? ? ? ? indexs.append(x)
return indexs
names= ['趙云','郭嘉','諸葛亮','曹操','趙云','孫權(quán)']
all_index= index(names,'趙云')
for xin all_index:
? ? names[x]= '子龍'
print(index(names,'關(guān)羽'))
print(names)
# 14.寫一個自己的max函數(shù)蹲蒲,獲取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
# 例如: 序列:[-7, -12, -1, -9]? ? 結(jié)果: -1
# 序列:'abcdpzasdz'? ? 結(jié)果: 'z'
# 序列:{'小明':90, '張三': 76, '路飛':30, '小花': 98}? 結(jié)果: 98
print(max([23,45,34,45]))
print(max({'name': '張三','zge': 16,'gender': '女'}))
def yt_max(seq):
? ? if isinstance(seq,dict):
? ? ? ? values= list(seq.values())
else:
? ? ? ? values= list(seq)
max1= values[0]
for itemin values[1:]:
? ? ? ? if item> max1:
? ? ? ? ? ? max1= item
return max1
print(yt_max([23,45,56,56]))
print(yt_max({'a','nsh','bccc'}))
print(yt_max({'小明': 90,'張三': 76,'路飛': 30,'小花': 98}))