python算法代码
时间: 2023-10-13 10:05:59 浏览: 94
以下是几种常见的Python算法代码示例:
1. 查找算法 - 二分查找
```python
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
```
2. 排序算法 - 冒泡排序
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
```
3. 递归算法 - 斐波那契数列
```python
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
```
4. 动态规划算法 - 最长递增子序列
```python
def longest_increasing_subsequence(arr):
n = len(arr)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if arr[i] > arr[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
```
5. 贪心算法 - 零钱兑换问题
```python
def coin_change(coins, amount):
coins.sort(reverse=True)
count = 0
for coin in coins:
count += amount // coin
amount = amount % coin
if amount != 0:
return -1
else:
return count
```
阅读全文