美文网首页
python-day-08作业

python-day-08作业

作者: sawyerwh | 来源:发表于2018-07-25 20:54 被阅读0次

    1.写⼀个函数将⼀个指定的列表中的元素逆序(例如[1, 2, 3] -> [3, 2, 1])(注意:不要使⽤列表⾃带的逆序函数)

    def reverse_list(list1):
        for index in range(len(list1)):
            # 取出对应的元素
            item = list1.pop(index)
            # 插入到最前面
            list1.insert(0, item)
    
    old_list = [1, 2, 3]
    reverse_list(old_list)
    print(old_list)
    
    

    2.写⼀个函数,提取出字符串中所有奇数位上的字符

    def get_char(str1):
        # 声明一个空串用来保存提取出来的字符
        new_str = str1[0::2]
        return new_str
    
    
    print(get_char('1name'))
    
    

    3.写⼀个匿名函数,判断指定的年是否是闰年

    is_leap_year = lambda year: (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)
    
    print('aaa',is_leap_year(2013))
    
    

    4.使⽤递归打印:
    n = 3的时候
    @
    @@@
    @@@@@
    n = 4的时候:
    @
    @@@
    @@@@@
    @@@@@@@

    def my_print(n, m=0):
        if n == 0:
            return None  # return 和 return None效果是一样的
    
        my_print(n-1, m+1)
        print(' '*m, end='')
        print('@'*(2*n-1))
    
    
    my_print(4)
    
    
    

    5.写函数,检查传⼊列表的⻓度,如果⼤于2,那么仅保留前两个⻓度的内容,并将新内容返回给调⽤者。

    def is_two(list1):
        if len(list1) <= 2:
            return list1
        else:
            list2 = []
            list2 = list1[0:2:]
            return list2
    list1 = [1,2,3,4,5]
    print(is_two(list1))
    

    6.写函数,利⽤递归获取斐波那契数列中的第 10 个数,并将该值返回给调⽤者。

    def get_number(n):
        if n == 1 or n == 2:
            return 1
    
        return get_number(n-1) + get_number(n-2)
    
    
    print(get_number(10))
    
    

    7.写⼀个函数,获取列表中的成绩的平均值,和最⾼分

    def get_score(scores):
        sum1 = 0
        return sum(scores)/len(scores), max(scores)
    
    
    ab,bc = get_score([1, 23, 50, 12])
    print(ab,bc)
    

    8.写函数,检查获取传⼊列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调者。

    def get_list_item(list1):
        list2 = list1[1::2]
        return list2
    list1 = [1,3,5,6,8,9]
    print(get_list_item(list1))
    

    相关文章

      网友评论

          本文标题:python-day-08作业

          本文链接:https://www.haomeiwen.com/subject/uxpmmftx.html