美文网首页
第十天作业

第十天作业

作者: xiongfei11111 | 来源:发表于2018-10-11 21:00 被阅读0次

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

def inverted(list1 :list):
    """
    使指定的列表中的元素逆序
    :param list1: list
    :return:list1: list
    """
    list1 = list1[::-1]
    return list1

print(inverted([1,2,3,4]))

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

def xf_str(str1 :str):
    """
    提取出有奇数位上的字符
    :param str1: str
    :return: str2 :str
    """
    str2 = ''
    for index in range(len(str1)):
        if index & 1:
            str2 += str1[index]

    return str2

print(xf_str('0123456789'))

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

leap_year = lambda n :('%d是闰年'%n) if((n % 4 == 0 and n % 100 != 0) or n % 400 == 0)else('%d不是闰年'%n)
print(leap_year(404))

4.使用递归打印:

n = 3
的时候


@
@ @ @
@ @ @ @ @


n = 4
的时候:


@
@ @ @
@ @ @ @ @
@ @ @ @ @ @ @

def xf_print(n: int):
    if n == 1:
        print('@' )
        return
    xf_print(n - 1)
    print('@'* (2*n-1))


print(xf_print(4))

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

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987

def xf_num(n :int):
    if n == 1or n==2:
        return 1
    num = xf_num(n-1) + xf_num(n-2)
    return num

re = xf_num(10)
print(re)

6.写一个函数,获取列表中的成绩的平均值,和最高分

def xf_num(list1 :list):
    x = sum(list1) / len(list1)
    i = max(list1)
    return x,i
num1 ,num2 = xf_num([1,2,3,4,5,])
print(num1,num2)

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

def xf_index(x):
    """
    检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新的列表返回给调用者
    :param x: list or tuple
    :return: list
    """
    list1 = []
    for index in range(len(x)):
        if index & 1:
            list1.append(x[index])
    return list1
my_list = xf_index([0,1,2,3,4,5,6,7,8,9])
my_tuple = xf_index((0,1,2,3,4,5,6,7,8,9))
print(my_list)
print(my_tuple)

8.实现属于自己的字典update方法:用一个字典去更新另一个字典的元素(不能使用自带的update方法)

def xf_update(dict1,dict2):
    for key in dict1:
        dict2[key] = dict1[key]
    return dict2

print(xf_update({'name1':'小明','age1':22,'score1':88},{'name2':'小红','age2':20,'score2':95}))

9.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)

def xf_items(dict1):
    list1 = []
    for key in dict1:
        tuple1 = key, dict1[key]
        list1.append(tuple1)
    return list1
print(xf_items({'a':1,'b':2,'c':3,'d':4}))

相关文章

网友评论

      本文标题:第十天作业

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