python第五章习题

5.1字符田字格绘制

点击查看代码
def print_grid(width):
    # 打印上边界
    print("+" + "-" * (width * 2 - 1) + "+")
    
    # 打印中间的横线
    for _ in range(width - 1):
        print("|" + " " * (width * 2 - 2) + "|")
    
    # 打印下边界
    print("+" + "-" * (width * 2 - 1) + "+")

# 调用函数,打印一个宽度为3的田字格
print_grid(3)
5.2奇数判断
点击查看代码
def isOdd(n):
    if isinstance(n, int):
        return n % 2 != 0
    return False
5.3质数判断
点击查看代码
def isPrime(n):
    if isinstance(n, int) and n > 1:
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return False
        return True
    return False
5.4质数列表
点击查看代码
def isPrime(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 PrimeList(N):
    primes = [i for i in range(2, N) if isPrime(i)]
    return ' '.join(map(str, primes))

# 调用函数,打印小于10的所有质数
print(PrimeList(10))
5.5字符质数判断
点击查看代码
def isNum(s):
    try:
        complex(s)
        return True
    except ValueError:
        return False
5.6数字积运算
点击查看代码
from functools import reduce
import operator

def multi(*args):
    return reduce(operator.mul, args, 1)
5.7斐波那契数列计算
点击查看代码
def FabNo(n):
    if n <= 1:
        return n
    else:
        return FabNo(n-1) + FabNo(n-2)
5.8数据类型判断
点击查看代码
def isType(obj):
    type_dict = {
        int: '整数',
        float: '小数',
        complex: '复数',
        str: '字符串',
        list: '列表',
        dict: '字典',
        set: '集合',
        tuple: '元组'
    }
    return type_dict.get(type(obj), '未知类型')
posted @ 2025-04-20 18:53  佘婷婷  阅读(18)  评论(0)    收藏  举报