Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – หาลำดับฟีบอนัชชีด้วยการเรียกซ้ำ (Recursion)

เมื่อต้องการหาลำดับฟีบอนัชชี (Fibonacci sequence) โดยใช้วิธีการเรียกซ้ำ (recursion) สามารถกำหนดฟังก์ชันที่เรียกตัวเองได้

ตัวอย่าง

def fibonacci_recursion(my_val):
    if my_val <= 1:
        return my_val
    else:
        return fibonacci_recursion(my_val - 1) + fibonacci_recursion(my_val - 2)

num_terms = 12
print("The number of terms is ")
print(num_terms)
if num_terms <= 0:
    print("Enter a positive integer...")
else:
    print("The Fibonacci sequence is :")
    for i in range(num_terms):
        print(fibonacci_recursion(i))

ผลลัพธ์

The number of terms is 12
The Fibonacci sequence is : 0 1 1 2 3 5 8 13 21 34 55 89

คำอธิบาย

  • กำหนดฟังก์ชัน fibonacci_recursion กรณีฐาน (base case): n<=1 คืนค่า n กรณีเรียกซ้ำ: คืนค่า fib(n-1) + fib(n-2)

  • กำหนดจำนวนพจน์ที่ต้องการ ตรวจสอบค่าบวก

  • วนลูป 0 ถึง num_terms-1 เรียกฟังก์ชัน recursive พิมพ์ผลลัพธ์แต่ละพจน์