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 13:24:53 浏览: 90
Python中_name==_main的解释
以下是对您提供的代码的改写版本:
```python
def split(params_str):
return list(map(int, params_str.split()))
def split_str(params_str):
return params_str.split()
n = int(input())
tree = {}
for _ in range(n):
input_temp = input()
temp = split_str(input_temp)
a, b = temp[0], temp[1]
tree.setdefault(b, []).append(a)
target = input()
childrens = tree.get(target, [])
result = []
while childrens:
node = childrens.pop(0)
result.append(node)
if node in tree:
childrens.extend(tree[node])
result.sort()
for res in result:
print(res)
```
在这个改写版本中,我使用了`split()`函数的`split()`方法替代了`find()`和循环,将字符串分割为整数列表。对于`split_str()`函数,我直接使用了`split()`方法将字符串分割为字符串列表。此外,使用了`setdefault()`方法来简化对树的构建过程,以及使用了`pop(0)`来替代了`childrens[0]`和`childrens[1:]`的操作。希望这样的改写能够更加简洁和高效地实现相同的功能。
阅读全文