以下是20个常用的Python脚本示例:
- 计算阶乘
python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
- 斐波那契数列
python
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
- 判断素数
python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7))
- 字符串反转
python
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
- 字符串大小写转换
python
def convert_case(s, case):
if case == "upper":
return s.upper()
elif case == "lower":
return s.lower()
else:
return s
print(convert_case("Hello", "lower"))
- 字符串替换
python
def replace_string(s, old, new):
return s.replace(old, new)
print(replace_string("hello world", "world", "python"))
- 列表排序
python
def sort_list(lst):
return sorted(lst)
print(sort_list([3, 1, 4, 2]))
- 列表去重
python
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4]))
- 列表合并
python
def merge_lists(lst1, lst2):
return lst1 + lst2
print(merge_lists([1, 2, 3], [4, 5, 6]))
- 列表切片
python
def slice_list(lst, start, end):
return lst[start:end]
print(slice_list([1, 2, 3, 4, 5], 1, 4))
- 字典键值对调换
python
def swap_dict(d):
return {v: k for k, v in d.items()}
print(swap_dict({"a": 1, "b": 2, "c": 3}))
- 计算圆的面积和周长
python
import math
def circle_area_circumference(radius):
area = math.pi * radius**2
circumference = 2 * math.pi * radius
return area, circumference
print(circle_area_circumference(5))
- 计算两个数的最大公约数和最小公倍数
python
def gcd_lcm(a, b):
gcd = a if b == 0 else gcd_lcm(b, a % b)
lcm = a * b // gcd
return gcd, lcm
print(gcd_lcm(12, 18))
- 计算矩阵乘法
python
def matrix_multiply(A, B):
return [[sum(a * b for a, b in zip(row_A, col_B)) for col_B in zip(*B)] for row_A in A]
print(matrix_multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]))
- 计算阶乘和
python
def factorial_sum(n):
return sum(range(1, n+1))
print(factorial_sum(5))
- 生成斐波那契数列的前n项
python
def generate_fibonacci(n):
return [fibonacci(i) for i in range(n)]
print(generate_fibonacci(10))
- 生成随机数列表
python
import random
def generate_random_list(n, start, end):
return [random.randint(start, end) for _ in range(n)]
print(generate_random_list(5, 1, 10))
- 生成九九乘法表
python
def print_multiplication_table():
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}x{i}={i*j}", end="\t")
print()
print_multiplication_table()
- 生成随机密码
python
import random
import string
def generate_password(length):
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
print(generate_password(8))
- 生成随机字符串
python
import random
import string
def generate_random_string(length):
return ''.join(random.choices(string.ascii_letters, k=length))
print(generate_random_string(8))