內容
數學集合各種運算以下列符號表示:

x 屬於(belong to)A 記做 x in A

A 與 B 聯集 (union) 記做 A + B

A 與 B 交集 (intersection) 記做 A * B

A 與 B 差集 (difference) 記做 A – B

A 包含(contain)B 記做 A >= B

製作一個「集合」類別(set class),使其能進行聯集、交集、差集、包含等運算。

輸入說明
每組測資的第一行 n 表示有 n 個集合,接著有 n 行分別為集合 A、B、C…的內容。

n=0 時表示輸入結束。

輸出說明
印出上述運算結果。

f-string 技巧

範例輸入 #1
2
abcdef
cfehi
2
34abcef
34
0
範例輸出 #1
Test Case 1:
A: {abcdef}
B: {cefhi}
A+B: {abcdefhi}
A*B: {cef}
A-B: {abd}
B-A: {hi}
A does not contain B
B does not contain A
Test Case 2:
A: {34abcef}
B: {34}
A+B: {34abcef}
A*B: {34}
A-B: {abcef}
B-A: {}
A contains B
B does not contain A

組合解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
count=1
while True:
n=int(input())
if n==0:
break
set_1=set(input())
set_2=set(input())
print('Test Case '+str(count)+':')
count+=1

temp_1=sorted(list(set_1))
print('A: {',end='')
print(*temp_1,sep='',end='')
print("}")

temp_2=sorted(list(set_2))
print('B: {',end='')
print(*temp_2,sep='',end='')
print("}")

#print(set_1,set_2)

# 聯集 union
print("A+B: {",end='')
temp_1=sorted(list(set_1|set_2))
print(*temp_1,sep='',end='')
print("}")

# 交集 intersection
print("A*B: {",end='')
temp_1=sorted(list(set_1&set_2))
print(*temp_1,sep='',end='')
print("}")

# 差集 difference(A-B)
print("A-B: {",end='')
temp_1=sorted(list(set_1-set_2))
print(*temp_1,sep='',end='')
print("}")

# 差集 difference(B-A)
print("B-A: {",end='')
temp_1=sorted(list(set_2-set_1))
print(*temp_1,sep='',end='')
print("}")

if set_2.issubset(set_1):
print('A contains B')
else:
print("A does not contain B")
if set_1.issubset(set_2):
print('B contains A')
else:
print("B does not contain A")

f-string 解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
count = 1
while True:
n = int(input())
if n == 0:
break
set_1 = set(input())
set_2 = set(input())
print(f'Test Case {count}:')
count += 1

temp_1 = sorted(list(set_1))
print(f"A: {{{''.join(temp_1)}}}")

temp_2 = sorted(list(set_2))
print(f"B: {{{''.join(temp_2)}}}")

# 聯集 union
temp_1 = sorted(list(set_1 | set_2))
print(f"A+B: {{{''.join(temp_1)}}}")

# 交集 intersection
temp_1 = sorted(list(set_1 & set_2))
print(f"A*B: {{{''.join(temp_1)}}}")

# 差集 difference(A-B)
temp_1 = sorted(list(set_1 - set_2))
print(f"A-B: {{{''.join(temp_1)}}}")

# 差集 difference(B-A)
temp_1 = sorted(list(set_2 - set_1))
print(f"B-A: {{{''.join(temp_1)}}}")

if set_2.issubset(set_1):
print('A contains B')
else:
print("A does not contain B")
if set_1.issubset(set_2):
print('B contains A')
else:
print("B does not contain A")

b050. 1. 集合運算


作者: 微風