递归

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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值