find the nth lucas number in python

One way to find the nth Lucas number in python is through recursion:

main.py
def lucas_number(n):
    if n == 0:
        return 2
    elif n == 1:
        return 1
    else:
        return lucas_number(n-1) + lucas_number(n-2)
150 chars
8 lines

However, this recursive approach can be inefficient for larger values of n. We can improve the performance of the solution by using dynamic programming:

main.py
def lucas_number(n):
    if n == 0:
        return 2
    elif n == 1:
        return 1
    else:
        a = 2
        b = 1
        for i in range(2, n+1):
            c = a + b
            a = b
            b = c
        return b
232 chars
14 lines

In this approach, we initialize the first two Lucas numbers and then use a loop to iteratively calculate the nth Lucas number. This approach has a time complexity of O(n) and is therefore more efficient than the recursive solution.

gistlibby LogSnag