python 编程实践-xyk 题目合集
整理与代码提供:华晓蔚 20230537 教师:刑永康
备注:考虑时间与可读性,未摘入题目内容,预祝大家考试顺利
part.1 作业题《Python 编程基础及应用实验教程》
备注:前两章简单题略去
7-4 猴子吃桃- 实验 3 简单的计算及输入输出
x = int(input())
remain = 1
for i in range(3):
remain = (remain + 1) /((100-x)/100)
print(f"猴子第1天摘得{int(remain)}个桃.")
7-5 游客检票 - 实验 3 简单的计算及输入输出
m = int(input())
n = int(input())
y = (8 * m - 6 * n) / (m - n)
x = 8 * m - y * m
z = x / (10 - y)
print(f"原有排队游客份数:{x:.1f}, \
每分钟新到游客份数:{y:.1f}, 10口同开需{z:.1f}分钟清零待检票游客.")
7-6 英文字母 - 实验 3 简单的计算及输入输出
Q = input()
N = int(input())
print(f"{Q}是字母表中第{ord(Q)-64}个字母.")
print(f"字母表中第{N}个字母是{chr(64 + N)}.")
7-7 橡皮泥 - 实验 3 简单的计算及输入输出
import math
diameter1 = float(input())
diameter2 = float(input())
volume = (4/3) * math.pi * ((diameter1 / 2)**3 + (diameter2 / 2)**3)
side_length = volume**(1/3)
print(f"正方体边长为:{side_length:.2f}.")
7-8 菲姐游泳 - 实验 3 简单的计算及输入输出
a, b, c, d = map(int, input().split())
total_minutes = (c - a) * 60 + (d - b)
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{hours}:{minutes:02}")
7-9 GPA 计算 - 实验 3 简单的计算及输入输出
total_grade_points = 0
total_credit_hours = 0
for _ in range(5):
course_name, score, credit_hour = input().split()
score = int(score)
credit_hour = int(credit_hour)
course_grade_point = 4.0 * (90 if score > 90 else score) / 90
total_grade_points += course_grade_point * credit_hour
total_credit_hours += credit_hour
gpa = total_grade_points / total_credit_hours
print(f"GPA:{gpa:.2f}")
7-1 不按常理出牌的列表 - 实验 4 装番茄和啤酒的容器
def in_strict(x, v):
for e in v:
if type(e) == type(x) and e == x:
return True
return False
v = list(eval(input()))
print("before:",v)
v = [x for i, x in enumerate(v) if not in_strict(x, v[i + 1:])]
print("after:",v)
7-1 闰年 - 实验 6 条件与分支
x = int(input())
if x % 4 == 0:
if x % 100 == 0:
if x % 400 == 0:
print("闰年")
else:
print("平年")
else:
print("闰年")
else:
print("平年")
7-2 印第安男孩 - 实验 6 条件与分支
n = int(input())
if n == 0 or n == 1:
print(f"{n} indian boy.")
elif n > 1:
print(f"{n} indian boys.")
7-3 超速罚款 - 实验 6 条件与分支
speed = int(input())
limit = int(input())
if speed <= limit :
print("未超速")
else:
overspeed_ratio = (speed - limit) / limit * 100
if overspeed_ratio <= 10:
print("超速警告")
elif overspeed_ratio <= 20:
print("罚款100元")
elif overspeed_ratio <= 50:
print("罚款500元")
elif overspeed_ratio <= 100:
print("罚款1000元")
else:
print("罚款2000元")
7-4 象限判定 - 实验 6 条件与分支
x, y = eval(input())
if x > 0 and y > 0:
print("第1象限")
elif x < 0 and y > 0:
print("第2象限")
elif x < 0 and y < 0:
print("第3象限")
else:
print("第4象限")
7-1 三天打渔、两天晒网 - 实验 7 简单的循环程序
def calculate_power(days):
guo_power = 100.00000
wang_power = 100.00000
for day in range(1, days + 1):
if day % 5 == 1 or day % 5 == 2 or day % 5 == 3:
guo_power = guo_power * 1.001
wang_power = wang_power * 1.002
else:
guo_power = guo_power * 1.001
wang_power = wang_power * 0.999
return guo_power,wang_power
N = int(input())
guo_power, wang_power = calculate_power(N)
# print(f"{guo_power:.5f},{wang_power:5f}")
print("{:.5f}".format(guo_power)+","+"{:.5f}".format(wang_power))
7-2 验证哥德巴赫猜想 - 实验 7 简单的循环程序
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
def find_prime_pair(N):
for i in range(2, N // 2 + 1):
if is_prime(i) and is_prime(N - i):
print(f"{N} = {i} + {N - i}")
break
N = int(input())
find_prime_pair(N)
7-1 词频统计 - 实验 11 字典操作及应用
import string
n = int(input())
word_count = {}
for _ in range(n):
text = input().lower()
for word in text.split():
cleaned_word = ''.join(char for char in word if char.isalpha())
if cleaned_word != '':
word_count[cleaned_word] = word_count.get(cleaned_word, 0) + 1
sorted_words = sorted(word_count.keys())
for word in sorted_words:
print(word, word_count[word])
6-1 富翁与骗子 - 实验 12 用函数实现模块化程序设计
def deposit(n):
total = 0
for i in range(1, n+1):
total += 2 ** (i-1)
return total / 100
def withdraw(n, amount):
return n * amount
6-2 求定积分通用函数 - 实验 12 用函数实现模块化程序设计
def f1(x):
return 1+x
def f2(x):
return 1/(1+4*x*x)
6-3 求 e 的 x 次方的近似数 - 实验 12 用函数实现模块化程序设计
def powers(x, n):
return x ** n
def fac(n):
if n == 0:
return 1
else:
return n * fac(n - 1)
6-1 掷骰子 - 实验 15 拥抱对象
class Dice:
def __init__(self):
self.iSides = 6
self.roll_results = []
def rollDice(self):
result = random.randint(1, self.iSides)
self.roll_results.append(result)
return result
def sideCount(self, side):
return self.roll_results.count(side)
def rollCount(self):
return len(self.roll_results)
6-1 德才兼备 - 实验 16 数据分析之排序
def classify(listT):
a, b, c, d = [], [], [], []
for m in listT:
pscore = int(m[1])
wscore = int(m[2])
if pscore >= 60 and wscore >= 60:
if pscore >= 80 and wscore >= 80:
a.append(m)
elif pscore >= 80:
b.append(m)
elif pscore >= wscore:
c.append(m)
else:
d.append(m)
return a, b, c, d
def admissionSort(a, b, c, d):
listA = []
for i in (a, b, c, d):
i.sort(key=lambda x: (-int(x[1]) - int(x[2]), -int(x[1]), int(x[0])))
listA.extend(i)
return listA
part.2 综合练习编程题《Python 编程基础及应用》
7-1 Life is short, I want to learn python (高教社,《Python 编程基础及应用》习题 2-5)
m="Life is short,I want to learn python!"
print(m)
7-2 成功就是从失败到失败,也依然不改热情! (高教社,《Python 编程基础及应用》习题 2-6)
print('丘吉尔说:"成功就是从失败到失败,也依然不改热情!"。')
7-3 My favorite sports are as follows (高教社,《Python 编程基础及应用》习题 2-7)
print('''My favorite sports are as follows:
\tfootball
\ttable tennis
\tbadminton
\tswimming
\trunning''')
7-4 小写到大写的转换 (高教社,《Python 编程基础及应用》习题 2-8)
input_string = input()
output_string = input_string.upper()
print(output_string)
7-5 编程从键盘读入 3 个整数,输出它们的和与平均值(高教社,《Python 编程基础及应用》习题 3-6)
a=int(input())
b=int(input())
c=int(input())
sum=a+b+c
avg =sum/3
print(f"{sum},{avg:.2f}")
7-6 鸡兔同笼(高教社,《Python 编程基础及应用》习题 3-7)
a=int(input())
b=int(input())
print(int(2*b-a/2))
print(int(a/2-b))
7-7 输入三角形三边长,求三角形面积(高教社,《Python 编程基础及应用》习题 3-8)
import math
a = float(input())
b = float(input())
c = float(input())
p = (a + b + c) / 2
s = p * (p - a) * (p - b) * (p - c)
if s > 0:
##由几何知识注意到这等价于三角形存在
triangle_area = math.sqrt(s)
print("{:.2f}".format(triangle_area))
else:
print("数据错误")
7-8 华氏温度到摄氏温度的转换(高教社,《Python 编程基础及应用》习题 3-9)
f = float(input())
c = 5/9 * (f - 32)
print("{:.1f}".format(c))
7-5 输入圆半径计算圆周长、圆面积、圆球表面积(高教社,《Python 编程基础及应用》习题 3-10)
import math
r = float(input())
print("{:.3f}".format(2 * math.pi * r))
print("{:.3f}".format(math.pi * r ** 2))
print("{:.3f}".format(4*math.pi * r ** 2))
7-6 英里到公里的转换(高教社,《Python 编程基础及应用》习题 3-11)
miles = float(input())
print("千米:{:.2f}".format(miles * 1.609))
7-7 最短跑道长度(高教社,《Python 编程基础及应用》习题 3-12
def calculate(v, a):
L = v**2 / (2*a)
return L
v = float(input())
a = float(input())
print("最短跑道长度为:{:.2f}".format(calculate(v, a)))
7-8 平面上的两点间距离计算(高教社,《Python 编程基础及应用》习题 3-13)
import math
x1, y1 = map(int, input().split(','))
x2, y2 = map(int, input().split(','))
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print("{:.2f}".format(distance))
7-13 输出 <=n 的全部回文数 (高教社,《Python 编程基础及应用》习题 4-5)
##法一:
n = int(input())
for num in range(n + 1):
num_str = str(num)
if num_str == num_str[::-1]:
print(num)
##法二:
n = int(input())
for num in range(n + 1):
bool = True
num_str = str(num)
length = len(num_str)
for i in range(length // 2):
if num_str[i] != num_str[length - i - 1]:
bool = False
break
if bool :
print(num)
7-14 列表生成及循环左移(高教社,《Python 编程基础及应用》习题 4-6)
##法一:
n = int(input())
num_list = list(range(1, n+1))
first_element = num_list.pop(0)
num_list.append(first_element)
print(num_list)
##法二:
a=eval(input())
list1=list(range(1,a+1))
jishu=0
n=0
for x in list1:
if jishu==0:
n=x
list1[jishu]=list1[jishu+1]
jishu+=1
elif jishu==len(list1)-1:
break
else:
list1[jishu]=list1[jishu+1]
jishu+=1
list1[jishu]=n
print(list1)
7-15 找列表中最大元素的下标(高教社,《Python 编程基础及应用》习题 4-7
num_list = list(map(int, input().split(',')))
max_num = max(num_list)
index_list = [index for index, num in enumerate(num_list) if num == max_num]
for index in index_list:
print(index)
7-16 删除列表中的重复值(高教社,《Python 编程基础及应用》习题 4-8)
##法一:(华晓蔚)
input_list = eval(input()) # 获取用户输入的列表
output_list = []
seen = set() # 用于跟踪已经出现过的元素
for item in reversed(input_list): # 反向遍历列表
if item not in seen: # 如果元素不在已经出现过的集合中
output_list.insert(0, item) # 在输出列表的开头插入元素
seen.add(item) # 将元素添加到已出现集合中
print(output_list) # 输出去重后的列表
##法二:
def in_strict(x, v):
for e in v:
if type(e) == type(x) and e == x:
return True
return False
v = list(eval(input()))
v = [x for i, x in enumerate(v) if not in_strict(x, v[i + 1:])]
print(v)
7-17 解析车间里的阀门状态 (高教社,《Python 编程基础及应用》习题 5-4)
##法一:(华晓蔚)
hex_input = input()
# 处理输入字符串,去掉无关字符,提取16进制数部分
hex_input = hex_input.replace('b', '')
hex_input = hex_input.replace('\'', '')
# 将16进制数转换为8位二进制字符串并补齐为8位
binary_string = bin(int(hex_input.split("\\x")[1], 16))[2:].zfill(8)
valve_states = []
# 从最后一位开始解析阀门状态
for i in range(7, -1, -1):
# 将字符 '1' 转换为True,其他字符转换为False
valve_states.append(binary_string[i] == '1')
print(valve_states)
##法二:
a=list(eval(input()))
for i in a:
b=bin(i)
b=list(b)
del b[0]
del b[0]
b.reverse()
lst2=b
jishu=0
for i in lst2:
if i=='1':
b[jishu]=True
elif i=='0':
b[jishu]=False
jishu+=1
c=8-len(b)
while c>0:
b.append(False)
c-=1
print(b)
7-18 身体质量指数(高教社,《Python 编程基础及应用》习题 6-3)
weight, height = map(float, input().split(','))
bmi = weight / (height ** 2)
if bmi < 18:
print('超轻')
elif 18 <= bmi < 25:
print('标准')
elif 25 <= bmi < 27:
print('超重')
else:
print('肥胖')
7-19 3,5,7 的倍数判定(高教社,《Python 编程基础及应用》习题 6-4)
num = int(input())
if num % 3 == 0 and num % 5 == 0 and num % 7 == 0:
print("Yes")
else:
print("No")
7-20 奖金计算,循环与多分支(高教社,《Python 编程基础及应用》习题 6-5)
profit = float(input())
bonus = 0.0
if profit <= 100000:
bonus = profit * 0.10
elif profit > 100000 and profit <= 200000:
bonus = 100000 * 0.10 + (profit - 100000) * 0.075
elif profit > 200000 and profit <= 400000:
bonus = 100000 * 0.10 + 100000 * 0.075 + \
(profit - 200000) * 0.05
elif profit > 400000 and profit <= 600000:
bonus = 100000 * 0.10 + 100000 * 0.075 + \
200000 * 0.05 + (profit - 400000) * 0.03
elif profit > 600000 and profit <= 1000000:
bonus = 100000 * 0.10 + 100000 * 0.075 + \
200000 * 0.05 + 200000 * 0.03 + \
(profit - 600000) * 0.015
elif profit > 1000000:
bonus = 100000 * 0.10 + 100000 * 0.075 + \
200000 * 0.05 + 200000 * 0.03 + \
400000 * 0.015 + (profit - 1000000) * 0.01
print("{:.2f}".format(bonus))
7-21 找出肇事者,循环与布尔逻辑(高教社,《Python 编程基础及应用》习题 6-6)
N = int(input())
for i in range(10 ** (N-1), 10 ** N-1):
l = str(i)
if l[0] == l[1] and int(l[N-1]) % 2 > 0 and \
int(l[N-1]) + int(l[N-2]) == 5 and i % 3 == 0:
print(l)
7-22 循环求 e 的近似值(高教社,《Python 编程基础及应用》习题 6-7)
import math
k = int(input())
e = 0
for n in range(k + 1):
e += 1 / math.factorial(n)
print("{:.10f}".format(e))
7-23 统计字符串列表中每个字母出现的次数(高教社,《Python 编程基础及应用》习题 6-8)
input_list = eval(input())
letter_count = {}
for string in input_list:
for letter in string:
if letter.islower():
letter_count[letter] = letter_count.get(letter, 0) + 1
for letter in sorted(letter_count):
print(f"{letter},{letter_count[letter]}")
7-24 情报加密(高教社,《Python 编程基础及应用》习题 6-10)
plaintext = input()
digits = [int(d) for d in plaintext]
encrypted_digits = [(d + 8) % 7 for d in digits]
encrypted_digits[0], encrypted_digits[4] = encrypted_digits[4],\
encrypted_digits[0]
encrypted_digits[1], encrypted_digits[2] = encrypted_digits[2], \
encrypted_digits[1]
encrypted_number = int("".join(map(str, encrypted_digits)))
print(encrypted_number)
7-25 考拉兹猜想(高教社,《Python 编程基础及应用》习题 6-11)
def collatz_sequence(n):
sequence = []
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(n)
return sequence
num = int(input())
result = collatz_sequence(num)
print(",".join(map(str, result)))
7-26 字典的应用-找出出现次数最多的字符串(高教社,《Python 编程基础及应用》习题 7-6)
strings = []
while True:
string = input()
if string == 'q':
break
strings.append(string)
string_count = {}
for s in strings:
string_count[s] = string_count.get(s, 0) + 1
max_string = max(string_count, key=string_count.get)
max_count = string_count[max_string]
print(max_string, max_count)
7-27 统计输入字符串中的单词个数及单词的平均长度(高教社,《Python 编程基础及应用》习题 7-7)
sentence = input()
words = sentence.split()
word_count = len(words)
total_length = sum(len(word) for word in words)
average_length = total_length / word_count if word_count > 0 else 0
print(f"{word_count},{average_length:.2f}")
part.3 综合练习函数题《Python 编程基础及应用》
6-1 列表推导生成矩形(高教社,《Python 编程基础及应用》习题 4-9)
def generateMatrix(m, n):
matrix = [[i + j + 2 for j in range(n)] for i in range(m)]
return matrix
6-2 列表推导生成随机数矩阵(高教社,《Python 编程基础及应用》习题 4-10)
def generateMatrix(m, n):
matrix = [[random.randint(1, 20) for j in range(n)] for i in range(m)]
return matrix
6-3 矩阵乘法函数(高教社,《Python 编程基础及应用》习题 4-11)
def multiply(a, b, p, q, r):
result = [[0 for _ in range(r)] for _ in range(p)]
for i in range(p):
for j in range(r):
for k in range(q):
result[i][j] += a[i][k] * b[k][j]
return result
6-4 数据打包与解包 (高教社,《Python 编程基础及应用》习题 5-3)
def pack(d):
if isinstance(d, list):
packed_data = bytearray(str(d), 'utf-8')
return packed_data
def unpack(d):
if isinstance(d, (bytearray, bytes)):
unpacked_data = eval(d.decode('utf-8'))
return unpacked_data
6-5 整数数位和(高教社,《Python 编程基础及应用》习题 8-3)
def digitSum(v):
num_str = str(v)
sum = 0
for digit_char in num_str:
digit = int(digit_char)
sum += digit
return sum
6-6 编写函数计算 f(i) = 1/2 + 2/3 + 3/4 + ... + i/(i+1) (高教社,《Python 编程基础及应用》习题 8-4)
def f(i):
result = 0.0
for n in range(1, i+1):
result += n / (n + 1)
return round(result, 4)
6-7 编写函数计算一个或不特定多个数的乘积(高教社,《Python 编程基础及应用》习题 8-6)
def caculate(*t):
result = 1
for num in t:
result *= num
return result
6-8 打印指定范围内的全部回文素数(高教社,《Python 编程基础及应用》习题 8-7)
def isPrime(num):
if num < 2:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
def reverseNumber(num):
return int(str(num)[::-1])
6-9 定义并实现身体质量指数类(高教社,《Python 编程基础及应用》习题 9-3)
class BMI:
def __init__(self, name, age, height, weight):
self.name = name
self.age = age
self.height = height
self.weight = weight
def getBMI(self):
return self.weight / (self.height * self.height)
def getStatus(self):
bmi = self.getBMI()
if bmi < 18:
return "超轻"
elif 18 <= bmi < 25:
return "标准"
elif 25 <= bmi < 27:
return "超重"
else:
return "肥胖"
6-10 定义并实现 Book 类及其__del__函数(高教社,《Python 编程基础及应用》习题 9-4)
class Book:
def __init__(self, title, book_no, price):
self.title = title
self.book_no = book_no
self.price = price
def __del__(self):
print(f"Book destroyed-{self.title},{self.book_no},{self.price:.2f}")
6-11 设计一元二次方程求解类(高教社,《Python 编程基础及应用》习题 9-4)
class Root:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def getDiscriminant(self):
return self.b ** 2 - 4 * self.a * self.c
def getRoot1(self):
discriminant = self.getDiscriminant()
return (-self.b + discriminant ** 0.5) / (2 * self.a)
def getRoot2(self):
discriminant = self.getDiscriminant()
return (-self.b - discriminant ** 0.5) / (2 * self.a)
6-12 设计一个股票类(高教社,《Python 编程基础及应用》习题 9-6)
class Stock:
"""Stock Information Class"""
def __init__(self, code, name, price_yesterday, price_today):
self.__code = code
self.__name = name
self.__price_yesterday = price_yesterday
self.__price_today = price_today
def getName(self):
return self.__name
def getCode(self):
return self.__code
def getPriceYesterday(self):
return self.__price_yesterday
def setPriceYesterday(self, price):
self.__price_yesterday = price
def getPriceToday(self):
return self.__price_today
def setPriceToday(self, price):
self.__price_today = price
def getChangePercent(self):
price_diff = self.__price_today - self.__price_yesterday
return price_diff / self.__price_yesterday
6-13 设计 Shape 基类及 Circle, Rectangle 继承类(高教社,《Python 编程基础及应用》习题 9-7)
import math
class Shape:
def __init__(self, sName):
self.sName = sName
class Rectangle(Shape):
def __init__(self, sName, length, width):
super().__init__(sName)
self.length = length
self.width = width
def getArea(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, sName, radius):
super().__init__(sName)
self.radius = radius
def getArea(self):
return math.pi * self.radius**2
6-14 设计学生类,使用类对象属性来记录学生对象的数量(高教社,《Python 编程基础及应用》习题 9-8)
class Student:
count = 0
def __init__(self, code, name):
self.code = code
self.name = name
Student.count += 1
def __del__(self):
Student.count -= 1
6-15 设计计数集合类,记录各元素加入集合的次数(高教社,《Python 编程基础及应用》习题 9-9)
from collections import defaultdict
class CountedSet(set):
def __init__(self):
super().__init__()
self.count_dict = defaultdict(int)
def add(self, element):
super().add(element)
self.count_dict[element] += 1
def getCount(self, element):
return self.count_dict[element]
6-16 根据三角形三边长求面积,不能合法构成三角形则抛出异常(高教社,《Python 编程基础及应用》习题 12-4)
try:
if a + b > c and a + c > b and b + c > a:
p = (a + b + c) / 2
ans = sqrt(p * (p - a) * (p - b) * (p - c))
else:
raise ValueError
part.4 综合实验《Python 编程基础及应用实验教程》
实验 19
import random
weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
m = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
def generateID():
sArea = str(random.randint(100000,999999))
sYear = str(random.randint(1900,2021))
sMonth = ['01','02','03','04','05','06','07','08','09','10','11','12'][random.randint(0,11)]
sDay = str(random.randint(1,28))
sDay = "0"*(2-len(sDay)) + sDay
sOrder = str(random.randint(0,999))
sOrder = "0"*(3-len(sOrder)) + sOrder
sID = sArea + sYear + sMonth + sDay + sOrder
sum = 0
for i in range(17):
sum += int(sID[i])*weights[i]
z = sum % 11
sID = sID + m[z]
return sID
f = open("ids.txt","wt")
for i in range(100000):
sID = generateID()
f.write(sID + "\n");
f.close()
print("100000 lines written to file ids.txt")
weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
m = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
def checkID(sID):
if len(sID)!=18:
return False
sum = 0
for i in range(17):
c = sID[i]
if ord(c)<ord('0') or ord(c)>ord('9'):
return False
sum += weights[i] * int(c)
z = sum % 11
if m[z] != sID[17]:
return False
return True
print("320124198808240056:", checkID("320124198808240056"))
print("360402197901160035:", checkID("360402197901160035"))
print("36040219160035:", checkID("36040219160035"))
print(":", checkID(""))
print("3604021979011600351234:", checkID("3604021979011600351234"))
print("360C0219160035:", checkID("360C0219160035"))
实验 20
morse = {
# Letters
"a": ".-","b": "-...","c": "-.-.","d": "-..","e": ".","f": "..-.","g": "--.",
"h": "....","i": "..","j": ".---","k": "-.-","l": ".-..","m": "--","n": "-.",
"o": "---","p": ".--.","q": "--.-","r": ".-.","s": "...","t": "-","u": "..-",
"v": "...-","w": ".--","x": "-..-","y": "-.--","z": "--..",
# Numbers
"0": "-----","1": ".----","2": "..---","3": "...--","4": "....-",
"5": ".....","6": "-....","7": "--...","8": "---..","9": "----.",
# Punctuation
"&": ".-...","'": ".----.","@": ".--.-.",")": "-.--.-","(": "-.--.",
":": "---...",",": "--..--","=": "-...-","!": "-.-.--",".": ".-.-.-",
"-": "-....-","+": ".-.-.",'"': ".-..-.","?": "..--..","/": "-..-.",
}
morseReverse = {}
for k,v in morse.items():
morseReverse[v] = k
def encode(s):
r = ""
for x in s:
if x == " ":
r += "/" #词间停顿
else:
r = r + morse[x] + "/" #空格表示字符间停顿
return r[:-1]
s = "Washington, this is pearl harbour, we are under japanese attack, japanese attack, repeat, repeat, this is not drill."
s1 = encode(s.lower())
print(s1)
def decode(s):
r = ""
words = s.split("//")
for word in words:
chars = word.split("/")
for c in chars:
r += morseReverse[c]
r += " "
return r
s2 = decode(s1)
print(s2)
import winsound,time,sys
def sendTelegram(s):
words = s.split("//")
for word in words:
chars = word.split("/")
for code in chars:
for x in code:
if x == ".":
winsound.Beep(1200,100)
else:
winsound.Beep(1200,300)
print(x,end="")
sys.stdout.flush()
print("/",end="")
time.sleep(0.3)
print("/",end="")
time.sleep(0.4)
sendTelegram(s1)
实验 21
d = []
with open('cellpicture.txt') as f:
m,n = map(int,f.readline().split())
for x in range(m):
r = list(map(int, f.readline()[:n]))
d.append(r)
for x in d:
print(x)
def explorePixel(d,m,n,i,j):
q = [(i,j)]
while q:
x,y = q.pop(0)
if d[x][y] < 0:
continue
d[x][y] = 0-d[x][y]
if x>0 and d[x-1][y]>0:
q.append((x-1,y))
if x<(m-1) and d[x+1][y]>0:
q.append((x+1,y))
if y>0 and d[x][y-1]>0:
q.append((x,y-1))
if y<(n-1) and d[x][y+1]>0:
q.append((x,y+1))
iCellCount = 0
for i in range(m):
for j in range(n):
if d[i][j] <= 0:
continue
iCellCount += 1
explorePixel(d,m,n,i,j)
print(iCellCount)
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于