函数式编程语言的亮点之一是递归,一种优雅的姿势
def fib(n: int) -> int:
if n == 0 or n == 1: # base case
return n
return fib(n-2) + fib(n-1)
def maximum(arr):
if not arr:
raise ValueError('Cannot find maximum in an empty list')
if len(arr) == 1:
return arr[0]
x, *tail = arr
max_tail = maximum(tail)
return x if x > max_tail else max_tail
arr = [1, 2, 3, 4]
x, tail = arr.pop(0), arr
# (1, [2, 3, 4])
Another option is to use slices on the list:
arr = [1, 2, 3, 4]
x, tail = arr[0], arr[1:]
# (1, [2, 3, 4])
arr = [1, 2, 3, 4] 。
x, tail = arr.pop(0), arr
# (1, [2, 3, 4])
另一个选择是在列表上使用片断。
arr = [1, 2, 3, 4].
x, tail = arr[0], arr[1:]
# (1, [2, 3, 4])
from typing import List
def minimum(arr: List[int]) -> int: # type annotations for clarity
x, *tail = arr # list unpacking
if not tail: # base case
return x
return min(x, minimum(tail)) # recursive call
def replicate(n, val):
if n <= 0:
return []
return [val, *replicate(n-1, val)]
Example invocation:
>>> replicate(3, 42)
[42, 42, 42]
def take(n, arr):
if n <= 0 or not arr:
return []
x, *tail = arr
return [x, *take(n-1, tail)]
>>> take(3, [0, 1, 2, 3, 4])
[0, 1, 2]
>> take(5, [])
[]
def elem(val, arr) -> bool:
if not arr:
return False
x, *tail = arr
if val == x:
return True
return elem(val, tail)
#Example invocation:
>>> arr1 = [1, 2, 3]
>>> arr2 = ['a', 'b', 'c', 'd']
>>> elem(0, arr1)
False
>>> elem('d', arr2))
True
def reverse(arr):
if not arr:
return []
x, *tail = arr
return [*reverse(tail), x]
Example invocation:
>>> reverse([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
>>> reverse([])
[]
def zip(xs, ys):
if not xs or not ys:
return []
x, *x_tail = xs
y, *y_tail = ys
return [(x, y), *zip(x_tail, y_tail)]
>> arr1 = [1, 2, 3]。
>> arr2 = ['a', 'b', 'c', 'd']
>> zip(arr1, arr2)
[(1, 'a'), (2, 'b'), (3, 'c')]
def quicksort(arr):
if not arr:
return []
x, *tail = arr
smaller_sorted = quicksort([t for t in tail if t <= x])
bigger_sorted = quicksort([t for t in tail if t > x])
return [*smaller_sorted, x, *bigger_sorted]
更多递归的文章>>
项目任务的递归>>
List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator
.
Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime
Args, Inline, Closure, Decorator, Class, Duck_Types, Enum, Exceptions
Print, Input, Command_Line_Arguments, Open, Path, Command_Execution.
CSV, JSON, Pickle, SQLite, Bytes, Struct, Array, MemoryView, D
**ARDUINO - 2021年5月17日项目课程近期发布
秋季及寒假初中级混班项目制
任务式学习课题一 糖纸换糖案例 学习循环控制 1 节课
丁丁猫亲子创客
计 算机编程 | VEX机器人 | 物联网
智能硬件 | 3D打印
NOIP竞赛
源著天街写字楼20栋8-13
上课地点
鸿恩寺校区:江北鸿恩寺保利江上明珠锦园一栋4-15
金科十年城校区:江北区石马河金科十年城56栋10-2
合作示范授课校区
两江春城校区:渝北区余溪路63-1小树苗乐学中心
晶郦馆校区:江北新南路163号水晶郦城A馆三楼
九街校区:江北区洋河东路1号揽胜国际广场2楼