https://www.codingame.com/training/easy/chuck-norris
최대한 내장함수를 사용하지 않고 코딩하려고 노력하였다.
문자를 ascii로 변환하기 위해서는 ord함수를 사용하고, 10진수를 2진수로 변환하기 위해서는 bin함수를 사용하면 된다. 다만 bin 함수 사용시 2진수 문자열 맨 앞에 "0b"가 추가되므로 이를 슬라이싱을 이용해 제거하고 사용하면 된다.
솔직히 chuck norris로 인코딩하는 코드는 테스트 케이스에서 에러가 날 때마다 덕지덕지 고쳐놔서 매우 지저분하다. 이런 것이 스파게티 코드인가? 책을 통해 공부하면서 code를 발전시켜봐야겠다.
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
message = input()
# 1. acili code로 변환
def toAscii(message):
decimal = ""
for char in message:
code = str(ord(char))
decimal = decimal + code
return decimal
# 2. ascii to binary
def toBinary(decimal):
binary = ""
decimal = int(decimal)
while decimal > 0 : # decimal이 0이 될 때까지 진행
reminder = str(decimal % 2)
binary = binary + reminder
decimal = decimal // 2
## test case 3, 4 중에 ascii 변환시 7비트가 되지 않는 경우가 있어서 방어코드 삽입
while len(binary) < 7:
binary = binary + "0"
return binary[::-1]
# 3. Chuck Norris로 변환
def checkBit(message):
result = ""
for bit in message:
if bit == "1":
result = result + "0" + " "
if len(message) == 1:
result= result + "0"
message = ""
else:
cnt = 1
for i in message[1:]:
if i == "1":
cnt += 1
else:
break
result = result + ("0" * cnt) + " "
message = message[cnt:]
return result, message
else:
result = result + "00" + " "
if len(message) == 1:
result= result + "0"
message = ""
else:
cnt = 1
for i in message[1:]:
if i == "0":
cnt += 1
else:
break
result = result + ("0" * cnt) + " "
message = message[cnt:]
return result, message
# 4. output
result = ""
## binary 변환
binaryMessage = ""
for char in message:
binaryMessage = binaryMessage + toBinary(toAscii(char))
## chuck norris 변환
while len(binaryMessage) != 0:
testResult, binaryMessage = checkBit(binaryMessage)
result = result + testResult
if result[len(result)-1] == " ":
result = result[:len(result)-1]
# Write an answer using print
# To debug: print("Debug messages...", file=sys.stderr, flush=True)
print(result)