# Recursive factorial functiondeffactorial(n):# Check the base case# Recursive casereturn n * factorial(n - 1)
deffactorial(n):# Check the base caseif n == 0:
return1# Recursive casereturn n * factorial(n - 1)
factorial25 = factorial(25)
'''
factorial25 : 15511210043330985984000000
'''
Fibonacci
用递归写出斐波拉契数
deffib(n):if n == 0or n == 1:
return1else:
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 iterationdeflength_iterative(ls):
count = 0whilenot ls.is_empty():
count = count + 1
ls = ls.tail()
return count
# Getting linked list length using recursiondeflength_recursive(ls):if ls.is_empty():
return0return1 + 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"