<think>根据用户需求,我们需要在myfunctions.py文件中编写以下函数:
1. 判断质数
2. 实现类似字符串split的功能
3. 判断三位水仙花数
4. 返回最小公倍数
5. 返回最大公约数
6. 输出九九乘法表
我们将分别编写这些函数,并确保每个函数的功能正确。
注意:在编写split函数时,参考引用[2]中提到的split方法,我们将实现一个类似的函数,可以指定分隔符和最大分割次数。
另外,判断水仙花数可以参考引用[1]中的方法。
由于用户要求将函数写在同一个文件中,我们将在一个代码块中展示整个myfunctions.py文件的内容。
下面开始编写代码:
</think>
# 功能函数集:myfunctions.py实现方案
下面是在`myfunctions.py`文件中实现的各类实用函数,包含质数判断、字符串分割、水仙花数验证、公倍数/公约数计算和乘法表输出功能。
```python
# myfunctions.py - 实用函数集合
def is_prime(n):
"""
判断一个数是否为质数
参数:
n: 正整数
返回:
bool: 如果是质数返回True,否则返回False
示例:
>>> is_prime(7)
True
>>> is_prime(8)
False
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# 只需检查到平方根
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def custom_split(s, sep=None, maxsplit=-1):
"""
实现类似str.split()的功能
参数:
s: 输入字符串
sep: 分隔符,默认为空格
maxsplit: 最大分割次数,-1表示不限制
返回:
list: 分割后的字符串列表
示例:
>>> custom_split("a b c")
['a', 'b', 'c']
>>> custom_split("1,2,3", sep=",", maxsplit=1)
['1', '2,3']
"""
result = []
current = ""
split_count = 0
for char in s:
# 达到最大分割次数时停止
if maxsplit >= 0 and split_count >= maxsplit:
current += char
continue
if sep and char == sep:
if current: # 避免空字符串
result.append(current)
current = ""
split_count += 1
elif sep is None and char.isspace():
if current: # 避免空字符串
result.append(current)
current = ""
split_count += 1
else:
current += char
# 添加最后一个部分
if current:
result.append(current)
return result
def is_narcissistic_number(n):
"""
判断一个三位数是否为水仙花数
水仙花数定义: 一个三位数等于各位数字的立方和
例如: 153 = 1³ + 5³ + 3³
参数:
n: 三位整数
返回:
bool: 如果是水仙花数返回True,否则返回False
示例:
>>> is_narcissistic_number(153)
True
>>> is_narcissistic_number(370)
True
>>> is_narcissistic_number(123)
False
"""
if n < 100 or n > 999:
return False
# 提取各位数字
hundreds = n // 100
tens = (n // 10) % 10
units = n % 10
# 计算立方和
total = hundreds**3 + tens**3 + units**3
return total == n
def gcd(a, b):
"""
计算两个数的最大公约数(GCD)
使用欧几里得算法
参数:
a, b: 正整数
返回:
int: a和b的最大公约数
示例:
>>> gcd(48, 18)
6
>>> gcd(17, 13)
1
"""
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
"""
计算两个数的最小公倍数(LCM)
参数:
a, b: 正整数
返回:
int: a和b的最小公倍数
示例:
>>> lcm(12, 18)
36
>>> lcm(5, 7)
35
"""
# 使用公式: LCM(a, b) = |a * b| / GCD(a, b)
return abs(a * b) // gcd(a, b) if a and b else 0
def print_multiplication_table():
"""
输出九九乘法表
示例输出:
1x1=1
1x2=2 2x2=4
...
"""
for i in range(1, 10):
for j in range(1, i + 1):
# 格式化输出,保持对齐
print(f"{j}x{i}={i*j}", end="\t")
print() # 换行
# 测试代码
if __name__ == "__main__":
# 测试质数函数
print("质数测试:", [n for n in range(1, 20) if is_prime(n)])
# 测试字符串分割
test_str = "apple,banana,orange,grape"
print("分割测试:", custom_split(test_str, sep=",", maxsplit=2))
# 测试水仙花数
print("水仙花数:", [n for n in range(100, 1000) if is_narcissistic_number(n)])
# 测试GCD和LCM
print("GCD(48, 18) =", gcd(48, 18))
print("LCM(12, 18) =", lcm(12, 18))
# 输出九九乘法表
print("\n九九乘法表:")
print_multiplication_table()
```
## 函数说明与数学原理
### 1. 质数判断 ($\text{is\_prime}$)
质数是只能被1和自身整除的大于1的自然数。函数使用以下优化:
- 排除小于2的数
- 单独处理2(唯一偶质数)
- 检查范围仅到 $\sqrt{n}$
- 跳过偶数检查(除2外)
### 2. 字符串分割 ($\text{custom\_split}$)
实现类似Python内置`split()`的功能:
- 支持自定义分隔符
- 控制最大分割次数
- 避免生成空字符串
- 处理空白符分隔(默认情况)
### 3. 水仙花数验证 ($\text{is\_narcissistic\_number}$)
水仙花数满足:
$$\text{abc} = a^3 + b^3 + c^3$$
其中 $\text{abc}$ 是三位数,$a$, $b$, $c$ 是其各位数字。
### 4. 最大公约数 ($\gcd$)
使用欧几里得算法:
$$\gcd(a, b) = \gcd(b, a \mod b)$$
直到 $b=0$ 时返回 $a$。
### 5. 最小公倍数 ($\text{lcm}$)
基于最大公约数计算:
$$\text{lcm}(a, b) = \frac{|a \times b|}{\gcd(a, b)}$$
### 6. 九九乘法表 ($\text{print\_multiplication\_table}$)
输出格式化的乘法表,使用嵌套循环实现。
## 使用示例
```python
from myfunctions import *
# 检查质数
print(is_prime(17)) # 输出: True
# 分割字符串
print(custom_split("hello world, how are you?", maxsplit=2))
# 输出: ['hello', 'world,', 'how are you?']
# 检查水仙花数
print(is_narcissistic_number(371)) # 输出: True
# 计算公约数和公倍数
print(gcd(56, 98)) # 输出: 14
print(lcm(15, 25)) # 输出: 75
# 打印乘法表
print_multiplication_table()
```
## 相关问题
1. 如何优化大数质数判断的性能[^1]?
2. 如何实现支持正则表达式的字符串分割函数?
3. 如何扩展水仙花数函数到任意位数?
4. 如何计算多个数的最大公约数和最小公倍数?
5. 如何将九九乘法表输出为HTML格式?
这些函数覆盖了基础数学运算、字符串处理和数值验证等常见需求,可直接集成到项目中或作为学习参考。