递归

来源:互联网 发布:语音识别算法视频教程 编辑:程序博客网 时间:2024/06/03 17:25

Factorials

  • 用递归写出阶乘
# Recursive factorial functiondef 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 namefirst_item = people.head().get_data()# Getting linked list length using iterationdef length_iterative(ls):    count = 0    while not ls.is_empty():        count = count + 1        ls = ls.tail()    return count# Getting linked list length using recursiondef 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 indexretrieval_by_index = "linear"# Retrieving an item in the linked list by valueretrieval_by_value = "linear"# Deleting an item from the linked list, with access to the item and #     the item before itdeletion = "constant"# Inserting an item into the linked list, with access to the location#     where we are insertinginsertion = "constant"# Calculating the length of a linked list using a looplength_iterative = "linear"# Calculating the length of a linked list using recursionlength_recursive = "linear"
0 0
原创粉丝点击