0%

中国矿业大学Python编程实践

2025 CUMT 中国矿业大学 Python 编程实践 代码题解

本博文由我的GitHub仓库LymoneLM/LymoneTest代码自动整理生成,进入仓库可以查看最新的代码

如果代码对您有帮助,希望可以给我的仓库点个Star,或者在GitHub关注我,感谢

在我的个人博客莱蒙黎梦可以查看本博文原文和更多其他我的博文

本博文提供的代码仅供参考学习,原题已遗失,先尝试后使用,不同年度课程题目可能略有差异

@[TOC]

Practice2

Practice2\1.py

1
2
3
4
5
6
7
str = input()
len = len(str)
flag = True
for i in range(len//2):
if str[i] != str[len-i-1]:
flag = False
print(flag)

Practice2\10.py

1
2
3
4
votes = [4, 7, 8, 1, 2, 2, 6, 2, 2, 1, 6, 8, 7, 4, 5, 5, 5, 8, 5, 5, 4, 2, 2, 6, 4]
candidate = int(input())
result = candidate in votes
print(result)

Practice2\11.py

1
2
3
grades = {'J01':88,'J02':60,'J03':80,'J04':96,'J05':86,'J06':75,'J07':76,'J08':82}
print(grades['J06'])
print(grades.values())

Practice2\12.py

1
2
3
month_days = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
month = int(input())
print(month_days[month])

Practice2\2.py

1
2
temp = float(input())
print("{:.2f}".format((temp-32)*5/9))

Practice2\3.py

1
2
3
4
5
6
7
rate, base, year = input().split(',')
rate = float(rate)
base = int(base)
year = int(year)
per_month = rate*base/(1-1/(1+rate)**(year*12))
print("{:.2f}".format(per_month))
print("{:.2f}".format(per_month*year*12))

Practice2\4.py

1
2
3
4
input = input()
len = len(input)
for i in range(len):
print(input[len-i-1],end="")

Practice2\5.py

1
2
3
4
5
6
7
input = input()
list = input.split(',')
num = 1
for i in input:
if i==",":
num+=1
print(f"{len(list)} {num}")

Practice2\6.py

1
2
3
4
5
6
input = input()
num = 0
for i in input:
if i == 'w' or i == 'W':
num+=1
print(num)

Practice2\7.py

1
2
3
4
input_str = list(input())
sorted_chars = sorted(input_str)
result = ' '.join(sorted_chars)
print(result)

Practice2\8.py

1
2
3
4
5
6
7
8
# scores = []
# for i in range(10):
# scores.append(float(input()))
scores = [8.5, 9, 9, 10, 7, 8, 8, 9, 8, 10]
scores.sort()
scores = scores[1:-1]
average = sum(scores) / len(scores)
print(f"{average:.2f}")

Practice2\9.py

1
2
3
4
5
6
7
scores = eval(input())
fail_scores = [s for s in scores if s < 60]
excellent_scores = [s for s in scores if s >= 90]
fail_avg = sum(fail_scores) / len(fail_scores) if fail_scores else 0
excellent_avg = sum(excellent_scores) / len(excellent_scores) if excellent_scores else 0
print(f"{fail_avg:.1f}")
print(f"{excellent_avg:.1f}")

Practice3

Practice3\1.py

1
2
3
x1, y1, x2, y2 = map(float, input().split(','))
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(f"{distance:.1f}")

Practice3\10.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
m1 = int(input())
m2 = int(input())
m3 = int(input())

avg = (m1 + m2 + m3) / 3

if avg > 95 or ((m1 == 100 and m2 == 100 and m3 >= 80) or
(m1 == 100 and m3 == 100 and m2 >= 80) or
(m2 == 100 and m3 == 100 and m1 >= 80)):
print("该同学获得一等奖学金。")
elif avg > 90 or ((m1 == 100 and m2 >= 75 and m3 >= 75) or
(m2 == 100 and m1 >= 75 and m3 >= 75) or
(m3 == 100 and m1 >= 75 and m2 >= 75)):
print("该同学获得二等奖学金。")
elif m1 >= 70 and m2 >= 70 and m3 >= 70:
print("该同学获得三等奖学金。")
else:
print("该同学没有获得奖学金。")

Practice3\2.py

1
2
3
4
5
pi = 3.14
r = float(input())
s = 4 * pi * r ** 2
v = 4 / 3 * pi * r ** 3
print(f"{s:.2f} {v:.2f}")

Practice3\3.py

1
2
3
n = int(input())
y = n ** (1/3) if n % 2 else n ** 0.5
print(f"y的值为:{y}")

Practice3\4.py

1
2
3
w = float(input())
y = w * 0.25 if w <= 50 else 50 * 0.25 + (w - 50) * 0.35
print(f"行李托运的运费是:{y}元")

Practice3\5.py

1
2
3
4
5
6
7
8
9
10
11
12
salary = int(input())
if salary <= 400:
f = salary * 0.005
elif salary <= 600:
f = salary * 0.01
elif salary <= 800:
f = salary * 0.015
elif salary <= 1500:
f = salary * 0.02
else:
f = salary * 0.03
print(f"工资{salary},应缴党费{f:.2f}元")

Practice3\6.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a, b, c = map(float, input().split(','))
if a + b > c and a + c > b and b + c > a:
if a == b == c:
print("三角形是等边三角形")
elif a == b or a == c or b == c:
if abs(a**2 + b**2 - c**2) < 1e-6 or abs(a**2 + c**2 - b**2) < 1e-6 or abs(b**2 + c**2 - a**2) < 1e-6:
print("三角形是等腰直角三角形")
else:
print("三角形是等腰非直角三角形")
elif abs(a**2 + b**2 - c**2) < 1e-6 or abs(a**2 + c**2 - b**2) < 1e-6 or abs(b**2 + c**2 - a**2) < 1e-6:
print("三角形是非等腰直角三角形")
else:
print("三角形是普通三角形")
else:
print("输入的三个数,不能作为三角形的边组成三角形。")

Practice3\7.py

1
2
3
4
5
6
7
8
9
10
11
12
13
M = int(input())
N = int(input())

if N % 2 != 0:
print("输入的脚数为奇数,不合理!")
else:
x = 2 * M - N // 2
y = M - x

if x < 0 or y < 0:
print("求出的只数为负,输入的数据不合理!")
else:
print(f"鸡有{x}只,兔有{y}只")

Practice3\8.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
year = int(input())
month = int(input())

if not (1000 <= year <= 2100 and 1 <= month <= 12):
print("输入的年份或月份不合法!")
else:
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(f"{year}{'是闰年' if is_leap else '不是闰年'}")

if month in [1, 2, 3]:
quarter = "第一"
elif month in [4, 5, 6]:
quarter = "第二"
elif month in [7, 8, 9]:
quarter = "第三"
else:
quarter = "第四"
print(f"{month}月是{quarter}季度")

if month == 2:
days = 29 if is_leap else 28
elif month in [4, 6, 9, 11]:
days = 30
else:
days = 31
print(f"{month}月有{days}天")

Practice3\9.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
a, b, c = map(float, input().split(','))

if a == 0 and b == 0:
print("方程无意义")
elif a == 0:
x = -c / b
print(f"方程有一个根:{x:.2f}")
else:
delta = b**2 - 4*a*c
if delta > 0:
x1 = (-b + delta**0.5) / (2*a)
x2 = (-b - delta**0.5) / (2*a)
print(f"方程有两个不等实根:x1={x1:.2f},x2={x2:.2f}")
elif delta == 0:
x = -b / (2*a)
print(f"方程有两个相等实根:x1={x:.2f},x2={x:.2f}")
else:
real = -b / (2*a)
imag = (-delta)**0.5 / (2*a)
x1 = complex(real, imag)
x2 = complex(real, -imag)
print(f"方程有两个不等虚根:x1=({x1:.2f}),x2=({x2:.2f})")

Practice4

Practice4\1.py

1
2
3
4
5
6
7
8
9
10
num = int(input())
original = num
reverse = 0

while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10

print(f"{original}的反序数是:{reverse}")

Practice4\10.py

1
2
3
4
5
6
7
8
9
for A in range(1, 10):
for B in range(0, 10):
for C in range(1, 10):
for D in range(0, 10):
ABCD = A * 1000 + B * 100 + C * 10 + D
CDC = C * 100 + D * 10 + C
ABC = A * 100 + B * 10 + C
if ABCD - CDC == ABC:
print(f"A={A} B={B} C={C} D={D}")

Practice4\11.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
M = int(input())
N = int(input())

if N % 2 != 0:
print("输入的脚数为奇数,不合理!")
else:
found = False
for chicken in range(M + 1):
rabbit = M - chicken
if 2 * chicken + 4 * rabbit == N:
print(f"鸡有{chicken}只,兔有{rabbit}只")
found = True
break

if not found:
print("求出的只数为负,输入的数据不合理!")

Practice4\12.py

1
2
3
4
5
6
7
8
9
10
11
M = int(input())
sequence = [1, 2, 3]
n = 3

while sequence[-1] <= M:
next_value = sequence[-1] + sequence[-2] + sequence[-3]
sequence.append(next_value)
n += 1

print(f"数列从第{n}项开始,数值超过{M}。")
print(f"第{n}项的值为{sequence[-1]}。")

Practice4\13.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
eps = float(input())
pi = 0
sign = 1
denominator = 1
term = 1

while abs(term) >= eps:
pi += term
sign *= -1
denominator += 2
term = sign / denominator

pi *= 4
print(f"近似值为:{pi}")

Practice4\14.py

1
2
3
4
5
6
7
8
9
10
11
12
13
import math

x = eval(input())
sin_x = 0
n = 1
term = x

while abs(term) >= 1e-6:
sin_x += term
n += 1
term = (-1)**(n+1) * x**(2*n - 1) / math.factorial(2*n - 1)

print(f"sin({x})的近似值为:{sin_x}")

Practice4\15.py

1
2
3
4
5
6
7
8
9
10
a = float(input())
eps = 1e-6
x_prev = a
x_next = 0.5 * (x_prev + a / x_prev)

while abs(x_next - x_prev) >= eps:
x_prev = x_next
x_next = 0.5 * (x_prev + a / x_prev)

print(f"x的近似值为:{x_next:.6f}")

Practice4\2.py

1
2
3
4
5
6
7
8
9
10
11
12
N = int(input())
K = 0
sum_squares = 0

while True:
K += 1
sum_squares += K * K
if sum_squares >= N:
K -= 1
break

print(f"最大K值是{K}")

Practice4\3.py

1
2
3
4
5
n = int(input())
for i in range(n + 1):
spaces = ' ' * (n - i)
numbers = str(i) * (2 * i + 1)
print(spaces + numbers)

Practice4\4.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a, b, c = eval(input())

def gcd(x, y):
while y:
x, y = y, x % y
return x

gcd_ab = gcd(a, b)
gcd_abc = gcd(gcd_ab, c)

lcm_ab = a * b // gcd_ab
lcm_abc = lcm_ab * c // gcd(lcm_ab, c)

print(f"最大公约数是{gcd_abc},最小公倍数是{lcm_abc}。")

Practice4\5.py

1
2
3
4
5
6
7
8
9
10
11
n = int(input())
result = []

for num in range(100, n + 1):
a = num // 100
b = (num // 10) % 10
c = num % 10
if num == a**3 + b**3 + c**3:
result.append(str(num))

print(' '.join(result))

Practice4\6.py

1
2
3
4
5
6
7
8
9
n = int(input())

for num in range(1, n + 1):
sum_factors = 0
for i in range(1, num):
if num % i == 0:
sum_factors += i
if sum_factors == num:
print(num)

Practice4\7.py

1
2
3
4
5
6
n = int(input())

for num in range(1, n + 1):
square = num * num
if str(num) == str(square)[-len(str(num)):] or str(num) == str(square):
print(num)

Practice4\8.py

1
2
3
4
5
6
7
8
9
10
11
12
n = int(input())

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

sum_primes = sum(num for num in range(2, n) if is_prime(num))
print(sum_primes)

Practice4\9.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import math

n = int(input())
pairs = []

for a in range(1, n + 1):
for b in range(a + 1, n + 1):
sum_ab = a + b
diff_ab = b - a
if math.sqrt(sum_ab) == int(math.sqrt(sum_ab)) and math.sqrt(diff_ab) == int(math.sqrt(diff_ab)):
pairs.append((a, b))

print(f"{n}以内的自然数对有:")
for pair in pairs:
print(pair[0], pair[1])

print(f"自然数对共有{len(pairs)}对。")

Practice5

Practice5\1.py

1
2
3
4
5
def is_odd(num):
return num % 2 != 0

n = int(input())
print(f"{n}{'奇数' if is_odd(n) else '偶数'}")

Practice5\10.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def isSymmetrical(lst):
for i in range(4):
for j in range(4):
if lst[i][j] != lst[j][i]:
return False
return True


def matrix_sum(lst):
total = 0
for i in range(4):
total += lst[i][i]
return total


if __name__ == "__main__":
matrix = []
for _ in range(4):
row = list(map(int, input().split(',')))
matrix.append(row)

if isSymmetrical(matrix):
print("矩阵是对称矩阵")
else:
print("矩阵不是对称矩阵")

print(f"矩阵对角线元素和是: {matrix_sum(matrix)}")

Practice5\11.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 递推法
def iterative_f(n):
total = 0.0
for i in range(1, n+1):
total += i / (2*i + 1)
return total

# 递归法
def recursive_f(n):
if n == 0:
return 0.0
return n / (2*n + 1) + recursive_f(n-1)

n = int(input())
print(f"递推法 f({n})= {iterative_f(n)}")
print(f"递归法 f({n})= {recursive_f(n)}")

Practice5\12.py

1
2
3
4
5
6
7
8
9
def resolve(n,x):
if n == 0:
return 1
if n == 1:
return x
return ((2 * n - 1) * x * resolve(n - 1, x) - (n - 1) * resolve(n - 2, x))/n
n = int(input())
x = float(input())
print(f"Legendre多项式的值: {resolve(n,x)}")

Practice5\2.py

1
2
3
4
5
6
7
8
9
10
def passed(score):
if score < 0 or score > 100:
return "输入的成绩错误!"
elif score >= 60:
return "该同学成绩合格啦!"
else:
return "该同学成绩不合格,需继续努力!"

score = int(input())
print(passed(score))

Practice5\3.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def string_num(ch):
letters = 0
digits = 0
spaces = 0
others = 0
for char in ch:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else:
others += 1
return letters, digits, spaces, others

ch = input()
letters, digits, spaces, others = string_num(ch)
print(f"统计结果:字母有{letters}个,数字有{digits}个,空格有{spaces}个,其他字符有{others}个。")

Practice5\4.py

1
2
3
4
5
6
7
8
9
10
def coprime(a, b):
while b:
a, b = b, a % b
return a == 1

a, b = map(int, input().split(','))
if coprime(a, b):
print(f"{a}{b}互质")
else:
print(f"{a}{b}不互质")

Practice5\5.py

1
2
3
4
5
6
7
8
9
10
def fib(n):
fib_list = []
a, b = 1, 1
for _ in range(n):
fib_list.append(a)
a, b = b, a + b
return fib_list

n = int(input())
print(fib(n))

Practice5\6.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def FacSum(n):
if n == 1:
return 0
sum_factors = 1
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
if i == n // i:
sum_factors += i
else:
sum_factors += i + n // i
return sum_factors

x = int(input())
pairs = set()

for a in range(2, x):
b = FacSum(a)
if b > a and FacSum(b) == a:
pairs.add((a, b))

for pair in sorted(pairs):
print(f"亲密数对: A={pair[0]:4}, B={pair[1]:4}")

Practice5\7.py

1
2
3
4
5
def huiwen(num):
return str(num) == str(num)[::-1]

M = int(input())
print(f"{M}{'是' if huiwen(M) else '不是'}回文数")

Practice5\8.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

a, b = map(int, input().split(','))
for num in range(a, b+1):
if num % 2 == 0:
for i in range(2, num//2 + 1):
if prime(i) and prime(num - i):
print(f"{num}={i}+{num-i}")
break

Practice5\9.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

def is_palindrome(n):
return str(n) == str(n)[::-1]

x = int(input())
count = 0
num = 2
result = []

while count < x:
if is_prime(num) and is_palindrome(num):
result.append(str(num))
count += 1
num += 1

for i in range(0, len(result), 10):
print(','.join(result[i:i+10]) + ',')

Practice6

Practice6\1.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class BMI:
def __init__(self, height, weight):
self.bmi = weight / (height ** 2)
def printBMI(self):
print("您的BMI指数是:{:.1f}".format(self.bmi))

class ChinaBMI(BMI):
def printBMI(self):
bmi_level = ["偏瘦","正常","偏胖","肥胖","重度肥胖"]
rate_level = ["低","平均水平","增加","中毒增加","严重增加"]
level = 0
if self.bmi < 18.5:
level = 0
elif self.bmi <= 23.9:
level = 1
elif self.bmi <= 26.9:
level = 2
elif self.bmi <= 29.9:
level = 3
else:
level = 4
print(f"您的BMI指数是:{self.bmi:.1f}\n"
f"{bmi_level[level]},相关疾病发病的危险性:{rate_level[level]}")
height = float(input())
weight = float(input())
person = ChinaBMI(height, weight)
person.printBMI()

Practice6\2.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Vehicle:
def __init__(self, speed, size, time, acceleration):
print(f"初速度:{speed} 加速度:{acceleration} 体积:{size}")
self.speed = speed
self.size = size
self.time = time
self.acceleration = acceleration

def move(self):
print(f"移动了:{self.speed * self.time}")

def setSpeed(self):
print(f"设置的初速度为:{self.speed}")

def speedUp(self):
print(f"加速完后速度是:{self.speed + self.acceleration * self.time}")

def speedDown(self):
print(f"减速完后速度是:{max(0, self.speed - self.acceleration * self.time)}")


speed = int(input())
size = int(input())
time = int(input())
acceleration = int(input())
v = Vehicle(speed, size, time, acceleration)
v.setSpeed()
v.speedUp()
v.speedDown()

Practice6\3.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return round(((self.x - other.x)**2 + (self.y - other.y)**2)**0.5, 2)

class Line:
def __init__(self, p1, p2):
dx = p1.x - p2.x
dy = p1.y - p2.y
self.k = None if dx == 0 else dy / dx
def relationship(self, other):
if self.k is None and other.k is None:
return "平行"
if self.k is None or other.k is None:
return "相交"
return "平行" if abs(self.k - other.k) < 1e-9 else "相交"

p = [Point(*map(float, input().split(','))) for _ in range(4)]
print(f"两点的欧式距离是{p[0].distance(p[1]):.2f}")
line1, line2 = Line(p[0], p[1]), Line(p[2], p[3])
print(line1.relationship(line2))

Practice7

Practice7\1.py

1
2
3
4
5
6
7
8
s = input().strip()
c, f = 0, True
for i in s:
if i == '(': c += 1
elif i == ')':
c -= 1
if c < 0: f = False; break
print('配对成功' if f and c == 0 else '配对不成功')

Practice7\2.py

1
2
3
4
5
6
7
8
9
10
n = int(input())
original = n
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d)**2 for d in str(n))
if n == 1:
print("{}是快乐数字".format(original))
else:
print("{}不是快乐数字".format(original))

Practice7\3.py

1
2
3
4
5
6
m, n, k = int(input()), int(input()), int(input())
people = list(range(1, m + 1))
index = 0
for _ in range(n):
index = (index + k - 1) % len(people)
print(f"{people.pop(index)}号下船了")

Practice7\4.py

1
2
3
4
5
6
7
8
9
10
11
12
13
nums = list(map(int, input().split(',')))
target = int(input())
found = False
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
print(f"和为目标值的两个整数的下标是 ({i}, {j})")
found = True
break
if found:
break
if not found:
print("和为目标值的两个整数的下标是 未找到")

Practice7\5.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 1
n = int(input())
pri = 1
for i in range(0, n):
pri += i
num = pri
print(num, end=" ")
for j in range(i + 2, n + 1):
num += j
print(num, end=" ")
print()
# 2
n = int(input())
matrix = [[0]*n for _ in range(n)]
num = 1
for d in range(n):
i = d
j = 0
while i >= 0:
matrix[i][j] = num
num += 1
i -= 1
j += 1
for row in matrix:
print(' '.join(map(str, filter(bool, row))),end=" \n")

Practice7\6.py

1
2
3
4
5
6
7
8
9
n = int(input())
m = list(map(int, input().split()))
x = list(map(int, input().split()))
current = {0}
for i in range(n):
mi = m[i]
xi = x[i]
current = {w + k * mi for w in current for k in range(xi + 1)}
print(len(current))

编程作业、大作业、课程设计程序代码调试、协助/指导,制作软件/脚本/网页,经验丰富

支持C/C++、JAVA、Python、Matlab、JavaScript、R语言等,欢迎咨询

-------------本文结束感谢您的阅读-------------

欢迎关注我的其它发布渠道