5.1-5.8

5.1
def drawaq(n):
line = 3n+1
for i in range(1,line+1):
if i%3 == 1:
print(n
"+----",end="")
print("+")
else:
print("| "*n,end="")
print("|")
n = eval(input("请输入阶数:"))
drawaq(n)

5.2
def isOdd(n):
return type(n) is int and n % 2 !=0
n = int(input("请输入整数:"))
print(isOdd(n))

import math
def isPrime(n):
if type(n) is not int or n < 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
sqrt_n = math.isqrt(n)
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
n = int(input("请输入整数:"))
print(isPrime(n))

import math

def PrimeList(N):
if type(N) is not int or N <= 1:
return ""
sieve = [True] * N
sieve[0], sieve[1] = False, False
for current in range(2, math.isqrt(N) + 1):
if sieve[current]:
sieve[currentcurrent : N : current] = [False] * len(sieve[currentcurrent : N : current])
primes = [str(i) for i, is_prime in enumerate(sieve) if is_prime]
return ' '.join(primes)
n = int(input("请输入整数:"))
print(PrimeList(n))

def isNum(s):
try:
int(s)
return True
except ValueError:
pass
try:
float(s)
return True
except ValueError:
pass
try:
complex(s)
if 'j' not in s.lower():
return False
parts = s.replace(' ', '').split('j')[0]
if parts and (parts[-1] in '+-') and len(parts) > 1:
return False
return True
except ValueError:
return False
n = input("请输入字符串:")
print(isNum(n))

def multi(*args):
product = 1
for num in args:
product = num
return product
n = input("请输入(用空格分隔):")
numbers = [float(x) for x in n.split()]
print(multi(
numbers))

5.7
def FabN(n):
if not isinstance(n, int):
raise TypeError("n 必须是整数")

def FabN(n):
if not isinstance(n, int):
raise TypeError("n 必须是整数")
if n < 0:
raise ValueError("n 不能为负数")
if n == 0:
return 0
elif n == 1:
return 1
return FabN(n-1) + FabN(n-2)
n = int(input("请输入一个整数:"))
print(FabN(n))

import ast

def isType(param):
param_type = type(param)
if param_type == int:
return '整数'
elif param_type == float:
return '小数'
elif param_type == complex:
return '复数'
elif param_type == str:
return '字符串'
elif param_type == list:
return '列表'
elif param_type == dict:
return '字典'
elif param_type == set:
return '集合'
elif param_type == tuple:
return '元组'
else:
return '未知类型'
try:
user_input = input("请输入数据:")
parsed_input = ast.literal_eval(user_input)
except (ValueError, SyntaxError):
parsed_input = user_input
print(isType(parsed_input))

posted @ 2025-04-21 22:14  穆斯221  阅读(22)  评论(0)    收藏  举报