46. 检查两个字符串是否是字母异位词
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent"))
print(are_anagrams("hello", "world"))
47. 计算一个数的阶乘
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
48. 生成一个包含前n个素数的列表
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
def generate_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
print(generate_primes(10))
49. 检查一个数是否为回文
def is_palindrome(n):
return str(n) == str(n)[::-1]
print(is_palindrome(121))
print(is_palindrome(123))
50. 计算两个日期之间的天数
from datetime import datetime
def days_between_dates(date1, date2):
date_format = "%Y-%m-%d"
d1 = datetime.strptime(date1, date_format)
d2 = datetime.strptime(date2, date_format)
return abs((d2 - d1).days)
print(days_between_dates("2023-01-01", "2023-12-31"))