[Python] zfill

토즐라·2022년 5월 3일
0

BOJ 16506 문제를 피를 토해가며 풀었다.
어렵지는 않았는데, 참 구현하는게 골때렸다.
일명 빡구현 문제로, 모든 단계를 직접 구현해가며 풀어야 하는 전형적인 삼성 코테 형식의 문제였다.

if __name__ == "__main__":
    n = int(input())
    for _ in range(n):
        object_code = ''
        operand = {"ADD":0, "ADDC":1, "SUB":2, "SUBC":3, "MOV":4, "MOVC":5, "AND":6, "ANDC":7, "OR":8, "ORC":9, "NOT":10, "MULT":12, "MULTC":13, "LSFTL":14, "LSFTLC":15, "LSFTR":16, "LSFTRC":17, "ASFTR":18, "ASFTRC":19, "RL":20, "RLC":21, "RR":22, "RRC":23}
        rA_except = ["MOV", "NOT"]

        assembly_code = list(input().split())

        tmp = bin(operand[assembly_code[0]])[2:]
        while len(tmp)<5:
            tmp = '0'+tmp
        object_code = object_code+tmp

        object_code = object_code+'0'

        tmp = bin(int(assembly_code[1]))[2:]
        while len(tmp)<3:
            tmp = '0'+tmp
        object_code = object_code + tmp
        if assembly_code[0] in rA_except:
            object_code = object_code+'000'
        else:
            tmp = bin(int(assembly_code[2]))[2:]
            while len(tmp)<3:
                tmp = '0'+tmp
            object_code = object_code+tmp
        if operand[assembly_code[0]]%2 == 0:
            tmp = bin(int(assembly_code[3]))[2:]+'0'
            while len(tmp)<4:
                tmp = '0'+tmp
            object_code = object_code + tmp
        else:
            tmp = bin(int(assembly_code[3]))[2:]
            while len(tmp)<4:
                tmp = '0'+tmp
            object_code = object_code + tmp
        print(object_code)

풀이가 너무 어처구니가 없어서 모법답안이 무엇인지 찾아보았다.

OP = {"ADD": 0, "ADDC": 1, "SUB": 2, "SUBC": 3, "MOV": 4, "MOVC": 5,
      "AND": 6, "ANDC": 7, "OR": 8, "ORC": 9, "NOT": 10, "MULT": 12,
      "MULTC": 13, "LSFTL": 14, "LSFTLC": 15, "LSFTR": 16, "LSFTRC": 17,
      "ASFTR": 18, "ASFTRC": 19, "RL": 20, "RLC": 21, "RR": 22, "RRC": 23}

for _ in range(int(input())):
    opcode, *reg = input().split()
    print(bin(OP[opcode])[2:].zfill(5)+'0')
    print(bin(int(reg[0]))[2:].zfill(3))
    print(bin(int(reg[1]))[2:].zfill(3))
    if opcode[-1] == 'C':
        print(bin(int(reg[2]))[2:].zfill(4)+'\n')
    else:
        print(bin(int(reg[2]))[2:].zfill(3)+'0\n')

내가 while문으로 돌려서 0을 채운 로직을 아주 간단하게 구현할 수 있는 zfill이라는 모듈이 있었다.

zfill

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.
If the value of the len parameter is less than the length of the string, no filling is done.

파이썬에서 숫자를 출력하고자 하는데, 앞에 0을 붙여주고 싶을 때 zfill(int n)이라는 함수를 이용하면 되는데, int n 자릿수를 맞춰서 숫자 앞에 0을 채워준다.

examples

#"002"
"2".zfill(3)
 
#"50000"
"50000".zfill(5)
 
#"00123"
"123".zfill(5)

Reference

profile
Work Hard, Play Hard 🔥🔥🔥

0개의 댓글