python经典算法实例
时间: 2024-08-14 17:02:36 浏览: 47
Python是一门广泛应用的数据分析、科学计算和人工智能语言,有许多经典的算法示例。以下是几个常见的算法及其Python实现:
1. **排序算法** - 如冒泡排序(Bubble Sort):
```python
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
# 示例
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = bubble_sort(numbers)
print(sorted_numbers)
```
2. **搜索算法** - 如二分查找(Binary Search):
```python
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# 如果元素大于中间值,则在左半部分继续查找
if arr[mid] < x:
low = mid + 1
# 如果元素小于中间值,则在右半部分继续查找
elif arr[mid] > x:
high = mid - 1
# 找到匹配项
else:
return mid
# 元素不在数组中
return -1
# 示例
arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
```
3. **动态规划算法** - 如斐波那契数列(Fibonacci Sequence):
```python
def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
n_terms = 10
print(fibonacci(n_terms))
```
阅读全文