递归

Factorials

  • 用递归写出阶乘
# Recursive factorial function
def factorial(n):
    # Check the base case

    # Recursive case
    return n * factorial(n - 1)
def factorial(n):
    # Check the base case
    if n == 0:
        return 1
    # Recursive case
    return n * factorial(n - 1)
factorial25 = factorial(25)
''' factorial25 : 15511210043330985984000000 '''

Fibonacci

  • 用递归写出斐波拉契数
def fib(n):
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1)+fib(n-2)
fib25 = fib(25)
''' 121393 '''

Linked List Length

  • 链表是一个递归结构数据类型,用递归来获取链表长度:
''' people : LinkedList (<class '__main__.LinkedList'>) <__main__.LinkedList at 0x7f69e8d56e48> '''
# First person's name
first_item = people.head().get_data()

# Getting linked list length using iteration
def length_iterative(ls):
    count = 0
    while not ls.is_empty():
        count = count + 1
        ls = ls.tail()
    return count

# Getting linked list length using recursion
def length_recursive(ls):
    if ls.is_empty():
        return 0
    return 1 + length_recursive(ls.tail())
people_length = length_recursive(people)

Linked List Time Complexity

# Retrieving an item in the linked list by index
retrieval_by_index = "linear"

# Retrieving an item in the linked list by value
retrieval_by_value = "linear"

# Deleting an item from the linked list, with access to the item and 
# the item before it
deletion = "constant"

# Inserting an item into the linked list, with access to the location
# where we are inserting
insertion = "constant"

# Calculating the length of a linked list using a loop
length_iterative = "linear"

# Calculating the length of a linked list using recursion
length_recursive = "linear"

你可能感兴趣的:(递归)