Comprehension and function assignments

Getting started N day

  1. Use list comprehensions to complete the following requirements:

    a. Generate a data list with the number of bits 3 in 1-100:

    # 结果为 [3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
    lits1=[i for i in range(1,100) if i%10==3]
    print(lits1)
    

    b. Use the list push to extract the integers in the list:

    # 例如:[True, 17, "hello", "bye", 98, 34, 21] --- [17, 98, 34, 21]
    list1=[True, 17, "hello", "bye", 98, 34, 21]
    list2=[i for i in list1 if type(i) == int]
    print(list2)
    

    c. Use list comprehension to store the length of the string in the specified list:

    # 例如 ["good", "nice", "see you", "bye"] --- [4, 4, 7, 3]
    list1=["good", "nice", "see you", "bye"]
    list2=[len(i) for i in list1]
    print(list2)
    

    d. dict_list = [{"Subject":"Politics", "Score":98}, {"Subject":"Chinese", "Score":77}, {"Subject":"Mathematics", "Score": 99}, {"Subject":"History", "Achievements":65}]

    Remove dictionaries with scores less than 70 in the list [list comprehension complete]

    # 结果为: [{“科目”:“政治”, “成绩”:98}, {“科目”:“语文”, “成绩”:77}, {“科目”:“数学”, “成绩”:99}]
    dict_list = [ {
          
          '科目':'政治', '成绩':98}, {
          
          '科目':'语文', '成绩':77},
                  {
          
          '科目':'数学', '成绩':99}, {
          
          '科目':'历史', '成绩':65}
                ]
    
    dict_list1=[grede for grede in dict_list if grede['成绩']>=70]
    print(dict_list1)
    
  2. Write a function to find the sum of 1+2+3+…N

    def my_sum(n):
        """
        求和
        :param n: 从1+到n
        :return: None
        """
        sums = 0
        for i in range(1, n + 1):
            sums += i
        print(f'它们的和是{sums}')
    
    
    my_sum(4)
    
  3. Write a function to find the maximum value among multiple numbers

    def my_max(*nums):
        """
        求多个数的最大值
        :param nums: 提供多个数
        :return: 
        """
        max_num=0
        for i in nums:
            if i>max_num:
                max_num=i
        print(max_num)
    my_max(1,3,55,7,9)
    
  4. Write a function to realize the function of rolling the dice, and print the points and the number of N dice

    import random
    
    
    def my_sums(num):
        """
        实现摇骰子的功能,打印N个骰子的点数和
        :param num: 提供需要的骰子数
        :return:None
        """
        sums1 = 0
        for i in range(num):
            _num = random.randint(1, 6)
            sums1 += _num
            print(f'随机数是{_num}')
        print(f'它们的和是{sums1}')
    
    
    my_sums(3)
    
  5. Write a function to exchange the key and value of the specified dictionary.

# 例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
def my_jh_dic():
  """
  交换字典中的键和值
  :return: None
  """
  dic1={
    
    'a':1, 'b':2, 'c':3}
  dic2=dict((i,dic1[i]) if type(dic1[i]) in (list,set,dict) else (dic1[i],i)  for i in dic1)
  print(dic2)
  
my_jh_dic()    
  1. Write a function to extract all the letters in a specified string, and then splice them together to produce a new string

    # 例如: 传入'12a&bc12d-+'   -->  'abcd'  
    def my_zm_str():
        """
        拼接字母字符串
        :return: 	None
        """
        str1='dsA3216'
        str2='12354jl'
        str3=''
        
        for i  in str1 :
            if 'A'<=i <='Z'or 'a'<=i<='z':
                str3+=i
        for j  in str2 :
            if 'A'<=j <='Z'or 'a'<=j<='z':
                str3+=j
        print(str3)
    my_zm_str()
    
  2. Write a function to find the average of multiple numbers

    def my_mean(*args):
        """
         求多个数的平均值
        :param args: 提供多个数
        :return: None
        """
        means=sum(args)/len(args)
        print(means)
    
    my_mean(1,2,3,4,5)
    
  3. Write a function that calculates the factorial of 10 by default, but also finds the factorial of other numbers

    def my_factorial(num=10):
        """
        求一个数的阶乘
        :param num: 默认值是10,也可以是其他数
        :return: None
        """
        num1=1
        for i in range(1,num+1):
            num1*=i
        print(num1)
        
        
    my_factorial(3)
    

=======Note: The following methods cannot use the methods and functions provided by the system, and all write their own logic

  1. Write your own capitalize function, which can turn the first letter of the specified string into uppercase letters

    # 例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
    def my_capitalize(str1):
        """
        将指定字符串首字母变成大写字母
        :param str1: 提供字符串
        :return: None
        """
        if str1:
            if 'a'<=str1[0]<='z':
                dx_a = chr(ord(str1[0]) - 32)
                str2 = dx_a + str1[1:]
                print(str2)
            else:
                print(str1)
        else:
            print("空串")
    
    
    my_capitalize('abc')
    my_capitalize('12asd')
    my_capitalize('')
    
  2. Write your own endswith function to determine whether a string has ended with the specified string

    # 例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
    #     字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
    def my_endswith(jw_str1, str2):
        """
        判断一个字符串是否以指定的字符串结束
        :param jw_str1: 提供结尾字符串
        :param str2: 提供需要判断的字符串
        :return: None
        """
        xb=-len(jw_str1)
        if jw_str1[-1]==str2[-1] and jw_str1[-1:0:-1]==str2[-1:xb:-1] :
            print(True)
        else:
            print(False)
    
    
    my_endswith('ab','abc2ab31ab')
    my_endswith('ab1','abc2ab31ab')
    
    
  3. Write your own isdigit function to determine whether a string is a pure digital string

    For example: '1234921' Result: True
    '23 function' Result:
    False'a2390' Result: False

def my_isdigit(strs):
 """
 判断一个字符串是否是纯数字字符串
 :param strs: 提供需要判断的字符串
 :return: None
 """
 str1 = ''
 for num in strs:
     if'0' <= num <= '9':
         str1 += num
 if len(str1) == len(strs) :
     print(True)
 else:
     print(False)


my_isdigit('1234921')
my_isdigit('a2390')
my_isdigit('23函数')
 
  1. Write your own upper function to turn all lowercase letters in a string into uppercase letters

    # 例如: 'abH23好rp1'   结果: 'ABH23好RP1'  
    def my_upper(strs):
        """
        将一个字符串中所有的小写字母变成大写字母
        :param strs: 提供一个字符串
        :return: None
        """
        str1=''
        for letter in strs:
            if 'a'<=letter<='z':
                letter=chr(ord(letter)-32)
            str1+=letter
        print(str1)
        
        
    my_upper('abH23好rp1')
                 
    
  2. Write your own rjust function to create a string with a specified length, the original string is right-aligned in the new string, and the remaining part is filled with specified characters

#  例如: 原字符:'abc'  宽度: 7  字符:'^'    结果: '^^^^abc'
#      原字符:'你好吗'  宽度: 5  字符:'0'    结果: '00你好吗'
def my_rjust(yzf_str,xzf_str,breadth):
 """
 在指定长度,原字符串在新字符串中右对齐,
 剩下的部分用指定的字符填充
 :param yzf_str:提供原字符串
 :param xzf_str:提供指定要添加的字符
 :param breadth:提供宽度
 :return:
 """
 if breadth<len(yzf_str):
     breadth=len(yzf_str)
 str3=xzf_str*(breadth-len(yzf_str))+yzf_str
 print(str3)
 
 
my_rjust(yzf_str='abc',xzf_str='*',breadth=7)
my_rjust(yzf_str='你好吗',xzf_str='0',breadth=5)                        
             
  1. Write your own index function to count all the subscripts of the specified element in the specified list. If there is no specified element in the list, return -1

    '''
    例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]  元素: 1   结果: 0,4,6  
         列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '赵云'   结果: 0,4
         列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '关羽'   结果: -1  
    '''
    def my_index(element, list2):
        """
        统计指定列表中指定元素的所有下标
        如果列表中没有指定元素返回 - 1
        :param element: 提供需要查找的元素
        :param list2:提供一个列表
        :return:None
        """
        if element in list2:
            lists = [i for i in range(len(list2)) if element == list2[i]]
            print(*lists)
        else:
            print(-1)
    
    
    my_index(1, [1, 2, 45, 'abc', 1, '你好', 1, 0])
    my_index('赵云', ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'])
    my_index('关羽', ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'])
           
    
  2. Write your own len function to count the number of elements in the specified sequence

    '''
    例如: 序列:[1, 3, 5, 6]    结果: 4
         序列:(1, 34, 'a', 45, 'bbb')  结果: 5  
         序列:'hello w'    结果: 7
    '''
    
    def my_len(sequence):
        """
        统计指定序列中元素的个数
        :param sequence: 提供需要统计的序列
        :return: None
        """
        count = 0
        for i in sequence:
            count += 1
        print(count)
    
    
    my_len([1, 3, 5, 6])
    my_len((1, 34, 'a', 45, 'bbb'))
    my_len('hello w')
    
  3. Write your own max function to get the maximum value of the elements in the specified sequence. If the sequence is a dictionary, take the maximum value of the dictionary

    '''
    例如: 序列:[-7, -12, -1, -9]    结果: -1   
         序列:'abcdpzasdz'    结果: 'z'  
         序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
    '''
    def my_max(sequence1):
        """
        获取指定序列中元素的最大值。
        如果序列是字典,取字典值的最大值
        :param sequence:提供一个序列
        :return:
        """
        if type(sequence1) == dict:
            sequence1 = sequence1.values()
        if type(sequence1) not in (list, tuple):
            sequence1 = list(sequence1)
        max_element = sequence1[0]
        for i in sequence1:
            if max_element <= i:
                max_element = i
    
        print(f'最大值:{max_element}')
    my_max([-7, -12, -1, -9])
    my_max('abcdpzasdz')
    my_max({
          
          '小明': 90, '张三': 76, '路飞': 30, '小花': 98})
    my_max({
          
          -7, -12, -1, -9})
       
    
    
    
    
    
    
    
    
    
  4. Write a function to implement your own in operation to determine whether the specified element exists in the specified sequence

    '''
    例如: 序列: (12, 90, 'abc')   元素: '90'     结果: False
         序列: [12, 90, 'abc']   元素: 90     结果: True 
    '''
    def my_in(strs,strs1):
        """
        判断指定序列中,指定的元素是否存在
        :param strs: 提供一个序列
        :param strs1: 提供一个指定元素
        :return: None
        """
        if type(strs)==dict:
            strs2=list(strs.keys())+list(strs.values())
            for i in strs2:
                if i == strs1:
                    num = True
                    break
                else:
                    num = False
            print(num)
        else:
            for i in strs:
                if i == strs1:
                    num = True
                    break
                else:
                    num = False
            print(num)
    my_in({
          
          '小明': 90, '张三': 76, '路飞': 30, '小花': 98},'小花')
    my_in({
          
          '小明': 90, '张三': 76, '路飞': 30, '小花': 98},98)
    my_in((12, 90, 'abc'),'90')
    my_in([12, 90, 'abc'],90)                
    
  5. Write your own replace function to convert the old string specified in the specified string into the specified new string.
    For example: Original string:'how are you? and you?' Old string:'you' New string: 'me' result:'how are me? and me?'

    # 方法一 利用字符串的函数先切割再添加
    def my_replace(strs, old_str, new_str):
        """
        将指定字符串中指定的旧字符串转换成指定的新字符串
        :param strs: 指定字符串
        :param old_str: 旧的字符串
        :param new_str: 新的字符串
        :return:None
        """
        lists = strs.split(old_str)
        new_strs = new_str.join(lists)
        print(new_strs)
    
    my_replace('how are you? and you?', 'you', 'me')    
    
    
# 方法二 
# 思路:利用while循环,定义一个下标,取一个字符判断后面连续字符是否与旧字符相等
# 不相等的就添加到新的字符串,同时下标加一位继续判断后面的字符
# 如果与旧字符相等,就替换为新字符,同时下标加旧字符的长度,继续判断后面的字符

def replace1(strs, old_str, new_str):
    new_str1 = ''
    o_len = len(old_str)
    index = 0
    while index < len(strs):
        if strs[index:len(old_str)+index]==old_str:
            new_str1+=new_str
            index+=o_len
        else:
            new_str1+=strs[index]
            index+=1
    print(new_str1)
    
    
replace1('how are you? and you?', 'you', 'me')




    
    
                      

    

    

Guess you like

Origin blog.csdn.net/weixin_44628421/article/details/109001922