def split(params_str): p = [] start = 0 end = params_str.find(' ') while end != -1: p.append(int(params_str[start:end])) start = end + 1 end = params_str.find(' ', start) p.append(int(params_str[start:])) return p def split_str(params_str): p = [] start = 0 end = params_str.find(' ') while end != -1: p.append(params_str[start:end]) start = end + 1 end = params_str.find(' ', start) p.append(params_str[start:]) return p n = int(input()) tree = {} for _ in range(n): input_temp = input() temp = split_str(input_temp) a = temp[0] b = temp[1] if b not in tree: tree[b] = [] tree[b].append(a) target = input() childrens = tree.get(target, []) result = [] while childrens: node = childrens[0] childrens = childrens[1:] result.append(node) if node in tree: childrens.extend(tree[node]) result.sort() for res in result: print(res) 加注释
时间: 2024-04-17 22:24:53 浏览: 102
String split函数
以下是您提供的代码添加注释后的版本:
```python
#义将字符串按空格分割成整数列表的函数
def split(params_str):
p = []
start = 0
end = params_str.find(' ')
while end != -1:
p.append(int(params_str[start:end]))
start = end + 1
end = params_str.find(' ', start)
p.append(int(params_str[start:]))
return p
# 定义将字符串按空格分割成字符串列表的函数
def split_str(params_str):
p = []
start = 0
end = params_str.find(' ')
while end != -1:
p.append(params_str[start:end])
start = end + 1
end = params_str.find(' ', start)
p.append(params_str[start:])
return p
# 获取输入的节点数
n = int(input())
tree = {}
# 构建树的字典结构
for _ in range(n):
input_temp = input()
temp = split_str(input_temp)
a = temp[0]
b = temp[1]
if b not in tree:
tree[b] = []
tree[b].append(a)
# 获取目标节点的子节点列表
target = input()
childrens = tree.get(target, [])
result = []
# 遍历获取目标节点的子孙节点,并添加到结果列表中
while childrens:
node = childrens[0]
childrens = childrens[1:]
result.append(node)
if node in tree:
childrens.extend(tree[node])
# 对结果进行排序并打印
result.sort()
for res in result:
print(res)
```
这个版本的代码添加了注释,以便更好地理解每个部分的功能和逻辑。希望这可以帮助您更好地理解代码的运行过程。
阅读全文