Advertisement
pacho_the_python

Fibonacci

Apr 20th, 2024
925
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. # Fibonacci Recursion
  2. def fibonacci_recursive(n):
  3.     if n <= 1:
  4.         return n
  5.     else:
  6.         return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
  7.  
  8.  
  9. def fibonacci_sequence(num):
  10.     if num <= 0:
  11.         return "Please enter a positive integer."
  12.     sequence = [fibonacci_recursive(i) for i in range(num)]
  13.     return f'{", ".join(map(str, sequence))}'
  14.  
  15.  
  16. print(fibonacci_sequence(11))
  17.  
  18.  
  19. # Fibonacci Generator
  20. def fibonacci(n):
  21.     """
  22.    Fibonacci Generator Function
  23.    """
  24.     a, b = 0, 1
  25.     count = 0
  26.     while count < n:
  27.         yield a
  28.         a, b = b, a + b
  29.         count += 1
  30.  
  31.  
  32. # Create a generator object
  33. fibonacci_generator = fibonacci(10)
  34.  
  35. # Generate and print the first 10 Fibonacci numbers
  36. fib_list = [n for n in fibonacci_generator]
  37. print(f"{', '.join(map(str, fib_list))}")
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement