Day10作业

2018-10-11  本文已影响0人  留级是不可能留级的

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

def reverse_order(list1: list):
    for x in range(0, int(len(list1)/2)):
        list1[x], list1[-1-x] = list1[-1-x], list1[x]
    return list1


list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(reverse_order(list2))
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(reverse_order(list2))

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

def extract_strings(strings: str):
    str1 = ""
    for x in range(len(strings)):
        if x % 2:
            str1 += strings[x-1]
    return str1
[图片上传中...(image.png-50ac3c-1539260009770-0)]


str2 = "abcdefghijklmn"
print(extract_strings(str2))

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

leap_year = lambda n: (n % 4 == 0 and n % 100 != 0) or (n % 400 == 0 and n % 3200 != 0)

print(leap_year(2000), leap_year(3200))

4.使用递归打印:

n = 3的时候   
   @    
  @@@  
 @@@@@ 
 
n = 4的时候: 
    @
   @@@
  @@@@@
 @@@@@@@

def triangle(n: int):
   n = 2 * n
   for x in range(1, n, 2):
       str1 = '@' * x
       str1 = str1.center(n - 1, " ")
       print(str1)


triangle(3)
triangle(4)

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

def fibonacci(n: int, x=2, fibonacci_list=[0, 1]):
    if x == n:
        return fibonacci_list[n - 2] + fibonacci_list[n - 1]
    else:
        y = fibonacci_list[x - 2] + fibonacci_list[x - 1]
        fibonacci_list.append(y)
        fibonacci(n, x + 1, fibonacci_list)
    return fibonacci_list[n-1]


print(fibonacci(10))

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

def max_avg(list1: list):
    avg = sum(list1)/len(list1)
    max1 = max(list1)
    return max1, avg


print(max_avg([1, 2, 3, 4, 5, 6, 7, 8]))

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

def check(list1):
    list2 = []
    for x in range(len(list1)):
        if x % 2:
            list2.append(list1[x])
    return list2


print(check([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

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

def check_dictionaries(dict1: dict, dict2: dict):
    for x in dict2.keys():
        print("x=",x)
        for y in list(dict1.keys())[:]:
            print("y=",y)
            if x == y:
                if dict2[x] == dict1[y]:
                    break
                else:
                    dict1[y] = dict2[x]
            else:
                dict1.setdefault(x, dict2[x])
    return dict1


dict3 = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, }
dict4 = {"a": 10, "b": 20, "f": 5, "d": 4, "h": 7, }
print(check_dictionaries(dict3, dict4))

9.实现属于自己的items方法:将字典转换成列表,字典中的键值对转换成元祖。(不能使用items方法)
yt_items(字典)
例如:{'a': 1, 'b':2, 'c':3} ---> [('a', 1), ('b', 2), ('c', 3)]

def lhw_items(dict1: dict):
    list1 = []
    for key in dict1.keys():
        tuple1 = (key, dict1[key])
        list1.append(tuple1)
    return list1


dict5 = {'a': 1, 'b': 2, 'c': 3}
print(lhw_items(dict5))
上一篇下一篇

猜你喜欢

热点阅读