題目連結

https://zerojudge.tw/ShowProblem?problemid=a131

https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=680#google_vignette

參考文章

X

本題要點

依照題目邏輯循序漸進編碼,我預設combine = [第一個字母, 0, 0, 0],接下來用迴圈查驗,若符合條件就更改對應數字(我用data[]來比對)

「3. 其餘的字母都必需編碼,除非它緊跟在一個編碼相同的字母之後」

如果「當前字母」與「前一個字母」編碼相同就忽略,combine不進行更改(因為不合法)。

參考解答

解一:

截圖 2024-06-20 下午5.51.06.png

data = [[], ["B", "P", "F", "V"], ["C", "S", "K", "G", "J", "Q", "X", "Z"], ["D", "T"], ["L"], ["M", "N"], ["R"]]
output = []
while True:
		try:
				name = input()
				combine = [name[0], 0, 0, 0]
				combine_idx = 1
				for idx in range(1, len(name)):
						if combine_idx > 3:
								break
						for i in range(1, 7):
								if name[idx] in data[i] and name[idx-1] not in data[i]:
										combine[combine_idx] = i
										combine_idx += 1
										break
						output.append([name, combine])
		
		except:
				break
print("NAME                     SOUNDEX CODE")
for op in output:
		print("        ",op[0],end = "")
		for i in range(25-len(op[0])):
				print(" ",end = "")
		for i in op[1]:
				print(i,end = "")
		print()
print("                   END OF OUTPUT")

回CPE頁面

CPE