本文實例講述了Python pygorithm模塊用法。分享給大家供大家參考,具體如下:
pygorithm:一個用純粹python編寫的Python模塊,用于純粹的教育目的。只需導入所需的算法即可獲取代碼,時間復雜度等等。開始學習Python編程的好方法。了解Python中所有主要算法的實現。不需要上網就可以獲得所需的代碼。
安裝
pip3 install pygorithm
常見函數
斐波那契數列
from pygorithm.fibonacci import recursionresult = recursion.get_sequence(10)print(result) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]code = recursion.get_code() # 獲取實現函數的算法print(code)
獲取最小公倍數
from pygorithm.math import lcmresult = lcm.lcm([4,6])print(result) # 12code = lcm.get_code() # 獲取實現函數的算法print(code)
質數算法
from pygorithm.math import sieve_of_eratosthenesresult = sieve_of_eratosthenes.sieve_of_eratosthenes(10) # 獲取小于10的質數print(result) # [2,3,5,7]code = lcm.get_code() # 獲取實現函數的算法print(code)
階乘
from pygorithm.math import factorialresult = factorial.factorial(5) # 獲取5的階乘,即1*2*3*4*5print(result) # 120code = factorial.get_code() # 獲取實現函數的算法print(code)
十進制轉二進制
from pygorithm.math import conversionresult = conversion.decimal_to_binary(3) # 將3轉換為二進制print(result) # 11code = conversion.get_code() # 獲取實現函數的算法print(code)
二進制轉十進制
from pygorithm.math import conversionresult = conversion.binary_to_decimal(11) # 將11轉換為十進制print(result) # 3code = conversion.get_code() # 獲取實現函數的算法print(code)
十進制轉十六進制
from pygorithm.math import conversionresult = conversion.decimal_to_hex(15) # 將15轉換為十六進制數print(result) # Fcode = conversion.get_code() # 獲取實現函數的算法print(code)
十六進制轉十進制
from pygorithm.math import conversionresult = conversion.hex_to_decimal("F") # 將十六進制F轉化為十進制數print(result) # 15code = conversion.get_code() # 獲取實現函數的算法print(code)
二分法搜索:效率高
from pygorithm.searching import binary_searchl = [9,4,5,1,7]index = binary_search.search(l,5) # 獲取5在列表中的位置,找到返回下標,找不到返回Falseprint(index)code = binary_search.get_code() # 獲取實現函數的算法print(code)
線性搜索:速度慢,適用性廣
from pygorithm.searching import linear_searchl = [9,4,5,1,7]index = linear_search.search(l,5) # 獲取5在列表中的位置,找到返回下標,找不到返回Falseprint(index)code = linear_search.get_code() # 獲取實現函數的算法print(code)
新聞熱點
疑難解答