PTA浙大版《Python 程序设计》题目集答案(一)-第1章-共3道题

本文提供了浙大版《Python程序设计》第1章的三道练习题的答案,包括输入两数求和、输入三数按公式输出及输出中文短语。代码实现详尽,适合初学者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

由于第一章较简单,不添加说明,后续如果较复杂,会附带解答思路。笔者能力有限,如果有错误和不同意见欢迎指正和交流。

第1章

第1章-1 从键盘输入两个数,求它们的和并输出 (30分)

本题目要求读入2个整数A和B,然后输出它们的和。
输入格式:
在一行中给出一个被加数
在另一行中给出一个加数
输出格式:
在一行中输出和值。
输入样例:
在这里给出一组输入。例如:
18
-48
输出样例:
在这里给出相应的输出。例如:
-30
代码:

a = int(input())
b = int(input())
c 
### PTA 团体程序设计天梯赛练习 Python 答案示例 #### 打印沙漏形状的解思路 为了实现将给定数量的特定字符按照沙漏形状打印的功能,可以采用逐层构建的方式。具体来说: - 需要计算每层所需的字符数并逐步减少直到中心最小层数再逐渐增加。 - 使用两个循环分别处理上半部分和下半部分。 以下是具体的Python代码实现[^1]: ```python def print_sandglass(char, total_chars): # 计算最大宽度(即最外层星星的数量) width = int((total_chars + 1) ** 0.5) current_width = width used_chars = 0 while True: line = char * min(current_width, total_chars - used_chars) if not line.strip(): break print(line.center(width)) used_chars += len(line.replace(&#39; &#39;, &#39;&#39;)) if current_width == 1 or used_chars >= total_chars: break current_width -= 2 if current_width > 1 else 0 current_width += 2 while current_width <= width and used_chars < total_chars: line = char * min(current_width, total_chars - used_chars) if not line.strip(): break print(line.center(width)) used_chars += len(line.replace(&#39; &#39;, &#39;&#39;)) current_width += 2 n = int(input().strip()) print_sandglass(&#39;*&#39;, n) ``` 此段代码实现了基于输入整数值`n`来创建相应大小的沙漏图案,并使用指定字符填充该结构。注意这里假设输入的是奇数个星号以便形成完美的上下对称图形;对于偶数情况可能需要额外逻辑调整以适应题目要求。 #### 处理性别配对问的解方法 针对另个关于性别匹配的问,则可以通过遍历列表找到符合条件的对象来进行输出操作。下面给出了种解决方案[^2]: ```python data = [] for _ in range(int(input())): info = input() gender = int(info[0]) person_name = info[2:] data.append([gender, person_name]) paired = set() for idx, item in enumerate(data): if idx in paired: continue target_gender = 1 - item[0] for other_idx, other_item in reversed(list(enumerate(data))): if other_item[0] == target_gender and other_idx not in paired: print(f"{item[1]} {other_item[1]}") paired.update({idx, other_idx}) break ``` 这段脚本读取多行字符串作为数据源,每行的第个字符代表性别(男或女),后面跟着的名字则是参与者姓名。通过两次迭代完成异性之间的两两组合输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值