008-函数练习题

  1. 编写一个函数,交换指定字典的key和value。

      例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
    
    # 解法1 使用dict.items()方法
    dict1={'a':1, 'b':2, 'c':3}
    new_dict={value:key for key,value in dict1.items()}
    print(new_dict)  # {1: 'a', 2: 'b', 3: 'c'}
    # 解法2 使用zip()方法
    dict1={'a':1, 'b':2, 'c':3}
    new_dict=dict(zip(dict1.values(),dict1.keys()))
    print(new_dict)  # {1: 'a', 2: 'b', 3: 'c'}
    # 解法3
    def exchange(dict1: dict):
        new_dict={}
        for key,value in dict1.items():
            # new_dict[key]=value
            new_dict[value]=key
        print(new_dict)
    exchange({'a':1, 'b':2, 'c':3})  # {1: 'a', 2: 'b', 3: 'c'}
    # 解法4
    def exchange_key_value(dict1: dict):
        for key in dict1.keys():
            value = dict1.pop(key)
            dict1[value] = key
        return dict1
    print(exchange_key_value({'a': 1, 'b': 2, 'c': 3}))  # {1: 'a', 2: 'b', 3: 'c'}
    
  2. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

       例如: 传入'12a&bc12d-+'   -->  'abcd'  
    
    # 解法1
    str2='12a&bc12d-+'
    str_2=''
    for i in str2:
        if 'a'<=i<='z' or 'A'<=i<='Z':
            str_2+=i
    print(str_2)  # abcd
    #解法2
    def isletter(str:str):
        new_str=''
        for i in str:
            if i.isalpha():
                new_str+=i
        print(new_str)  
    isletter('12a&bc12d-+') # abcd
    
  3. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

      例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    
    # 解法1
    str3=input('请输入字符串:')
    print(str3.capitalize())
    # 解法2
    str3=input('请输入字符串:')
    str_3=''
    if str3[0].isalpha():
        str_3=chr(ord(str3[0])-32)+str3[1:]
    else:
        str_3=str3
    print(str_3)
    # 解法3
    def Upper(str: str):
        if str[0].islower():
            return  str[0].upper() + str[1:]
        else:
            return str
    print(Upper('12asd'))  # 12asd
    print(Upper('abv'))  # Abv
    
  4. 写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束

       例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
            字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    
    # 解法1
    str4='abc231ab'
    str_4=input('请输入字符串:') # ab
    print(str4.endswith(str_4)) # True
    # 解法2
    str4='abc231ab'
    str_4=input('请输入字符串:') # ab
    len1=len(str4)
    len2=len(str_4)
    if str4[len1-len2:]==str_4:
        print(True)
    else:
        print(False)
    # 解法3
    def isend(str1:str,str2:str):
        len1=len(str1)
        len2=len(str2)
        if str1[len1-len2:]==str2:
            print(True)
        else:
            print(False)
    isend('abc231ab','ab') # True
    isend('abc231ab','ab1') # False
    # 解法4
    def endswith(str1: str, end: str):
        n = len(end)
        str[-n:]   #取到字符串的最后n位
        return str1[-n:] == end
    print(endswith('abc231ab', 'ab'))  # True
    
  5. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串

       例如: '1234921'  结果: True
             '23函数'   结果: False
             'a2390'    结果: False
    
    # 解法1
    str5=input('请输入字符串:')
    print(str5.isdigit())
    # 解法2
    str5=input('请输入字符串:')
    if str5!='':
        for i in str5:
            if not '0'<=i<='9':
                print(False)
                break
        else:
            print(True)
    else:
        print(False)
    # 解法3
    def is_digit(str: str):
        return str.isdigit()
    print(is_digit('21345343'))  # True
    print(is_digit('ef函数'))  # False
    print(is_digit('a1232fa'))  # False
    
  6. 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母

        例如: 'abH23好rp1'   结果: 'ABH23好RP1'   
    
    # 解法1
    str6='abH23好rp1'
    print(str6.upper()) # ABH23好RP1
    # 解法2
    str6='abH23好rp1'
    str_6=''
    for i in str6:
        if 'a'<=i<='z':
            str_6+=chr(ord(i)-32)
        else:
            str_6+=i
    print(str_6)  # ABH23好RP1
    # 解法3
    def all_upper(str:str):
        new_str=''
        for i in str:
            if i.islower():
                new_str+=chr(ord(i)-32)
            else:
                new_str+=i
        print(new_str) 
    
    all_upper('abH23好rp1')  #  ABH23好RP1
    
  7. 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

       例如: 原字符:'abc'  宽度: 7  字符:'^'    结果: '^^^^abc'
            原字符:'你好吗'  宽度: 5  字符:'0'    结果: '00你好吗'
    
    def rjust(str: str, num: int, str1: str):
        len1 = num - len(str)
        if len1 < 0:
            return str
        return str1 * len1 + str
    print(rjust('abc', 7, '^'))  # ^^^^abc
    print(rjust('你好吗', 5, '0'))  # 00你好吗
    
  8. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1

       例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]  元素: 1   结果: 0,4,6  
            列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '赵云'   结果: 0,4
            列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '关羽'   结果: -1         
    
    def index(list: list, element):
        new_list = [i for i in range(len(list)) if list[i] == element]
        if new_list:
            return new_list
        else:
            return -1
    print(index([1, 2, 45, 'abc', 1, '你好', 1, 0], 1))  # [0, 4, 6]
    print(index(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'], '赵云'))  # [0, 4]
    print(index(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'], '关羽'))  # -1
    
    
    
  9. 写一个自己的len函数,统计指定序列中元素的个数

        例如: 序列:[1, 3, 5, 6]    结果: 4
             序列:(1, 34, 'a', 45, 'bbb')  结果: 5  
             序列:'hello w'    结果: 7
    
    def my_len(order):
        count = 0
        for i in order:
            count += 1
        return count
    print(my_len([1, 3, 5, 6]))  # 4
    print(my_len((1, 34, 'a', 45, 'bbb')))  # 5
    print(my_len('hello w'))  # 7
    
  10. 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

       例如: 序列:[-7, -12, -1, -9]    结果: -1   
            序列:'abcdpzasdz'    结果: 'z'  
            序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
    
    # 解法1
    def max_num(xulie):
        if type(xulie) == list:
            return max(xulie)
        elif type(xulie) == str:
            return max(xulie)
        elif type(xulie) == dict:
            max1 = 0
            for key, value in xulie.items():
                if value > max1:
                    max1 = value
            return max1
    print(max_num([-7, -12, -1, -9]))  # -1
    print(max_num('abcdpzasdz'))  # z
    print(max_num({'小明': 90, '张三': 76, '路飞': 30, '小花': 98}) ) # 98
    # 解法2
    def my_max(seq):
        if type(seq)==dict:
            seq=list(seq.values())
        else:
            seq=list(seq)
        max1=seq[0]
        for i in seq:
            if i>max1:
                max1=i
        return max1
    print(my_max([-7, -12, -1, -9]))  # -1
    
  11. 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在

        例如: 序列: (12, 90, 'abc')   元素: '90'     结果: False
             序列: [12, 90, 'abc']   元素: 90     结果: True     
    
    def my_in(order, order1):
       if order1 in order:
           return True
       else:
           return False
    print(my_in((12, 90, 'abc'), '90'))  # False
    print(my_in([12, 90, 'abc'], 90))  # True
    
  12. 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串

        例如: 原字符串: 'how are you? and you?'   旧字符串: 'you'  新字符串:'me'  结果: 'how are me? and me?'
    
    def str_replace(str:str,n_str,o_str):
        new_str=''
        len1=len(o_str)
        i=0
        for _ in range(len(str)-len1-1):
            if str[i:i+len1]==o_str:
                new_str+=n_str
                i+=len1
            else:
                new_str+=str[i]
                i+=1
        print(new_str)
    str_replace('how are you? and you?','me','you') # how are me? and me?
    # 解法2 强烈安利 so easy
    def str_replace(str: str, n_str, o_str):
       return  n_str.join(str.split(o_str))
    print(str_replace('how are you? and you?', 'me', 'you'))  # how are me? and me?
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兮知

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值