作业10day

1.编写函数,求1+2+3+…N的和


def yt_sum1(n):

    return sum(range(1,n+1))

print(yt_sum1(10))

2.编写一个函数,求多个数中的最大值


def yt_max(*nums):

    max1= nums[0]

for num in nums[1:]:

        if num> max1:

            max1= num

return max1

print(yt_max(19,992,-93,0))
  1. 编写一个函数,交换指定字典的key和value

dict1= {'a': 1,'b': 2}# {1: 'a', 2: 'b'}

def exchange_key_value(dictx: dict):

    # 注意: 遍历删除和增加,遍历对象应该原来没有进行修改的原容器的值。

    for keyin dictx.copy():

        value= dictx[key]

print(key)

dictx.pop(key)

dictx[value]= key

exchange_key_value(dict1)

print(dict1)

9.写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束

例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True

字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: 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函数,判断一个字符串是否是纯数字字符串

例如: '1234921' 结果: True

'23函数' 结果: False

'a2390' 结果: False

def isdigit(str1: str):

    for charin str1:

        if not '0' <= char<= '9':

            return False

    return True

print(isdigit('2a333'))

12.写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

例如: 原字符:'abc' 宽度: 7 字符:'^' 结果: '^^^^abc'

原字符:'你好吗' 宽度: 5 字符:'0' 结果: '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函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1

例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0] 元素: 1 结果: 0,4,6

列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '赵云' 结果: 0,4

列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '关羽' 结果: -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= ['赵云','郭嘉','诸葛亮','曹操','赵云','孙权']

all_index= index(names,'赵云')

for xin all_index:

    names[x]= '子龙'

print(index(names,'关羽'))

print(names)

14.写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

例如: 序列:[-7, -12, -1, -9] 结果: -1

序列:'abcdpzasdz' 结果: 'z'

序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 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}))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。