zoukankan      html  css  js  c++  java
  • (二)2-4练习小结

    1、实现1-100的所有的和

    sum = 0
    for i in range(101):
        sum +=i
    print(sum)

    运行结果:

    5050

     2、实现1-500所有奇数的和

    sum = 0
    for i in range(1,501,2):
        sum +=i
    print(sum)

    运行结果:

    62500

    3、求1+ 2! + 3! + 4! + ……20!的和

    def myfact(n):
        if n < 0:
            print("负数没有阶乘!!!")
        elif n <2 :
            return  1
        else :
            return  n * myfact(n-1)
    def get_sum(m):
        sum = 0
        for i in range(1,m+1):
            sum  += myfact(i)
        return  sum
    print(get_sum(20))

    运行结果:

    2561327494111820313

    4、对指定一个list进行排序[2,32,43,453,54,6,576,5,7,6,8,78,7,89]

    list1 = [2,32,43,453,54,6,576,5,7,6,8,78,7,89]
    print(type(list1))
    list1.sort(reverse=False)
    print(list1)
    list2 = [2,32,43,453,54,6,576,5,7,6,8,78,7,89]
    list2.sort(reverse=True)
    print(list2)
    print('*'*30)

    运行结果:

    <type 'list'>
    [2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]
    [576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]

    5、字典排序

    dic = {"d":87,"a":54,"c":15,"b":99,"e":66}
    #按字典键排序
    a = sorted(dic.items(),key=lambda x:x[1],reverse=False)
    print(a)
    #按字典值排序
    a = sorted(dic.items(),key=lambda x:x[0],reverse=False)
    print(a)

    运行结果:

    [('c', 15), ('a', 54), ('e', 66), ('d', 87), ('b', 99)]
    [('a', 54), ('b', 99), ('c', 15), ('d', 87), ('e', 66)]

  • 相关阅读:
    字典转模型
    iOS开发之---传值大全
    UITableViewCell重用机制
    通知/代理/block 三者比对
    内存的那些事
    C++
    C#接口实现案例
    4.2 C#-----------------------------操作符的重载------------------------------------------
    C#抽象类和抽象方法的实现
    C#----析构函数
  • 原文地址:https://www.cnblogs.com/pythonlx/p/7739742.html
Copyright © 2011-2022 走看看