编写Python算法通常涉及以下步骤:
定义问题:
明确算法要解决的问题和目标。
设计算法:
根据问题设计出算法逻辑,可能包括数据结构的选择、算法的正确性和效率。
编写代码:
将算法逻辑转换为Python代码。
测试代码:
通过测试确保代码的正确性和效率。
下面是一些具体的Python算法示例:
斐波那契数列
def fibonacci(n):
a, b = 0, 1
while b < n:
a, b = b, a + b
return a
输出第10个斐波那契数
print(fibonacci(10)) 输出:55
水仙花数
def is_narcissistic(num):
digits = [int(d) for d in str(num)]
return num == sum(d len(digits) for d in digits)
输出所有的水仙花数
for i in range(100, 1000):
if is_narcissistic(i):
print(i)
分解质因数
def prime_factors(n):
factors = []
divisor = 2
while n > 1:
while n % divisor == 0:
factors.append(divisor)
n //= divisor
divisor += 1
return factors
输出90的质因数
print(prime_factors(90)) 输出:[2, 3, 3, 5]
快速排序算法
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
示例数组
array = [3,6,8,10,1,2,1]
print(quick_sort(array)) 输出:[1, 1, 2, 3, 6, 8, 10]
二分查找算法
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
示例有序数组和目标值
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 5
print(binary_search(array, target)) 输出:4
PSI公式计算
import numpy as np
def psi_score(expected, actual):
expected_counts = np.histogram(expected, bins=10)
actual_counts = np.histogram(actual, bins=10)
expected_proportions = expected_counts / np.sum(expected_counts)
actual_proportions = actual_counts / np.sum(actual_counts)
index = np.sum((actual_proportions - expected_proportions) * np.log(actual_proportions / expected_proportions))
return index
示例数据
expected = np.random.normal(size=1000)
actual = np.random.normal(size=1000)
计算PSI
print(psi_score(expected, actual))
以上示例展示了如何用Python实现不同的算法。每个算法都有其特定的应用场景和实现细节,需要根据实际需求进行选择和调整。