递归小列
Posted zqxqx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了递归小列相关的知识,希望对你有一定的参考价值。
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)
方法二
#!/urs/bin/env python # -*- coding:utf-8 -*- import functools result = (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(5) print(result)
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)
方法二
#!/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()
以上是关于递归小列的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript - 代码片段,Snippets,Gist