zoukankan      html  css  js  c++  java
  • 小列

    1 用递归求5!

    方法一

    #!/urs/bin/env python
    # -*- coding:utf-8 -*-
    
    
    def factorial(num):
        """
        求5的阶乘
        :param num: 
        :return: 
        """
        if num < 5:
            return num*factorial(num+1)
        else:
            return num
    if __name__ == "__main__":
        evaluation = factorial(1)
        print(evaluation)
    View Code

     方法二

    #!/urs/bin/env python
    # -*- coding:utf-8 -*-
    import functools
    result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(5)
    print(result)
    View Code

    2  [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, **, **, **, **, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99],查找一个数字,如果找到则打印该数字,如果找不到,则输出“not found!”

    方法一

    #!/urs/bin/evn python
    # -*- coding:utf-8 -*-
    
    # c = [] 测试
    number = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
    
    
    def name(num):
        for i in number:
            if num == i:
                return num
        else:
            return "not found!"
    if __name__ == "__main__":
        while True:
            number1 = int(input("请输入要判断的数在不在:"))
            results = name(number1)
            print("查询结果:%s" % results)
    View Code

    方法二

    #!/urs/bin/evn python
    # -*- coding:utf-8 -*-
    number_list = [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
    
    
    def search(num_list, num):
        """
        查找num的值是否在num_list中,二分法。
        :param num_list:
        :param num:
        :return:
        """
        lower = 0
        upper = len(num_list)-1
        if lower == upper:
            if num == num_list[upper]:
                return True
            else:
                return False
        else:
            middle = upper//2
            if num < num_list[middle]:
                num_list = num_list[:middle]
                return search(num_list, num)
            if num > num_list[middle]:
                num_list = num_list[middle+1:]
                return search(num_list, num)
            else:
                return True
    
    
    def main():
        """
        主程序
        :return: 
        """
        while True:
            num = input(">>:").strip()
            try:
                num = int(num)
            except:
                raise TypeError("请输入数字")
            if search(number_list, num):
                print("%d存在列表中" % num)
            else:
                print("该值不存在")
    if __name__ == "__main__":
        main()
    View Code
  • 相关阅读:
    053403
    053402
    053401
    053400
    053399
    053398
    053397
    053396
    053395
    第k小数
  • 原文地址:https://www.cnblogs.com/zqxqx/p/8778090.html
Copyright © 2011-2022 走看看