1.编写函数,求1+2+3+…N的和
def yt_sum1(n):
sum1 = 0
for x in range(1, n+1):
sum1 += x
return sum1
result = yt_sum1(100)
print(result)
2.编写一个函数,求多个数中的最大值
def yt_max(*nums):
"""
求多个数中的最大值
:param nums: 所有的数字
:return: 最大值
"""
# nums = ()
# nums = (10, 29, 78, 9)
if not nums:
return None
max1 = nums[0]
for num in nums[1:]:
if num > max1:
max1 = num
return max1
result1 = yt_max()
result2 = yt_max(10, 29, 78, 9)
print(result1, result2)
- 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
def shake_plug(n: int):
"""
摇n个骰子,求点数和
:param n: 骰子的个数
:return: 点数和
"""
sum1 = 0
for _ in range(n):
num = random.randint(1, 6)
sum1 += num
return sum1
print(shake_plug(3))
4.编写一个函数,交换指定字典的key和value。
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def exchange_dict(dict1: dict):
"""
交换字典的key和value
:param dict1: 需要交换的字典
:return: None
"""
for key in dict1.copy():
value = dict1.pop(key)
dict1[value] = key
dict1 = {'a': 1, 'b': 2, 'c': 3}
exchange_dict(dict1)
print(dict1)
5.编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
def get_letter(str1: str):
"""提取字符串中的字母"""
new_str = ''
for ch in str1:
if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
new_str += ch
return new_str
print(get_letter('ah&89s9Kol0==='))
print(get_letter('ah&sHUka02-2KL==='))
- 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如: 'abc' -> 'Abc' '12asd' --> '12asd'
def capitalize(str1: str):
"""
将字符串的第一个字符从小写字母变成大写字母
:param str1: 字符串
:return: 新字符串
"""
if not str1:
return str1
ch = str1[0]
if 'a' <= ch <= 'z':
ch = chr(ord(ch) - 32)
return ch+str1[1:]
print(capitalize('abc'))
2.写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
def endswith(str1: str, end: str):
"""判断字符串结尾"""
end_length = len(end)
if str1[-end_length:] == end:
return True
return False
print(endswith('abc321', '321'))
3.写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
例如: '1234921' 结果: True
'23函数' 结果: False
'a2390' 结果: False
def isdigit(str1: str):
for ch in str1:
if not('0' <= ch <= '9'):
return False
return True
print(isdigit('abc23')) # False
print(isdigit('273838')) # True
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
print('======第1题.day-10作业======')
def element(seq, element):
for item in seq:
if item == element:
return True
else:
print('False')
element((12, 90, 'abc'), 90)
def replace_func(str1: str, old_str: str, result_str: str):
i = 0
new_str = ''
length1 = len(str1)
length2 = len(old_str)
while i < length1:
if str1[i:i + length2] == old_str:
new_str += result_str
i += length2
continue
new_str += str1[i]
i += 1
return new_str
print(replace_func('how are you? and you?', 'you', 'me'))