python演算法之遞迴演算法
阿新 • • 發佈:2018-12-11
# -*- coding: utf-8 -*- import numpy as np # 遞迴演算法 i = 0 def my_Recursion(list, n): global i try: if list[i] == n: # 基線條件 return i, i+1 else: # 遞迴條件 i += 1 return my_Recursion(list, n) except Exception as e: print(e) if __name__ == '__main__': x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print('row data:{}\nlength of data:{}'.format(x, len(x))) print('Please input the number that you want to know : ') y = int(input()) temp = my_Recursion(x, y) try: print('查詢到{}在資料中的位置為{},查詢步數為{}步'.format(y, temp[0], temp[1])) except Exception as e: print('This number is not in the data!\n', e)
其中,在使用遞迴演算法的時候,可能會出現return返回數值為None的情況,這時候需要修改的地方為其遞迴條件處,將其用return返回的方法來呼叫本體。這樣就可以消除出現None的情況。
我曾經跨過山和大海,也穿過人山人海,我曾經擁有著的一切,轉眼都飄散如煙,我曾經失落失望失掉所有方向,直到看見平凡才是唯一的答案。 ——韓寒《平凡之路》