pta团体程序设计天梯赛-练习集答案python
时间: 2025-06-30 11:34:38 浏览: 7
### 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(' ', ''))
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(' ', ''))
current_width += 2
n = int(input().strip())
print_sandglass('*', 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
```
这段脚本读取多行字符串作为数据源,每行的第一个字符代表性别(男或女),后面跟着的名字则是参与者姓名。通过两次迭代完成异性之间的两两组合输出。
阅读全文
相关推荐











