写一个程序完成以下命令: new id ——新建一个指定编号为id的序列(id<10000) add id num——向编号为id的序列加入整数num merge id1 id2——合并序列id1和id2中的数,并将id2清空 unique id——去掉序列id中重复的元素 每行输出的末尾没有空格
时间: 2023-10-21 13:03:30 浏览: 63
以下是 Python3 的实现代码:
```python
class Sequence:
def __init__(self):
self.sequences = {}
def new(self, id):
if id not in self.sequences and id < 10000:
self.sequences[id] = []
print("Succeeded")
else:
print("Failed")
def add(self, id, num):
if id in self.sequences:
self.sequences[id].append(num)
print("Succeeded")
else:
print("Failed")
def merge(self, id1, id2):
if id1 in self.sequences and id2 in self.sequences:
self.sequences[id1] += self.sequences[id2]
self.sequences[id2] = []
print("Succeeded")
else:
print("Failed")
def unique(self, id):
if id in self.sequences:
self.sequences[id] = list(set(self.sequences[id]))
print("Succeeded")
else:
print("Failed")
sequence = Sequence()
while True:
try:
command = input().split()
if command[0] == "new":
sequence.new(int(command[1]))
elif command[0] == "add":
sequence.add(int(command[1]), int(command[2]))
elif command[0] == "merge":
sequence.merge(int(command[1]), int(command[2]))
elif command[0] == "unique":
sequence.unique(int(command[1]))
except:
break
```
使用时,输入命令即可。例如,输入
```
new 1
add 1 1
add 1 2
unique 1
merge 2 3
```
输出结果为:
```
Succeeded
Succeeded
Succeeded
Succeeded
Failed
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)