포스트

[Python] Programmers - Repeating binary conversion

This post explains how to count removed zeros and binary conversion steps in Python, including a simpler solution using bin().

한국어 원문은 여기에서 볼 수 있습니다.
[Python] Programmers - Repeating binary conversion

Programmers 이진 변환 반복하기

Solution

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
def solution(s):
    answer = []
    z_cnt = 0
    cnt = 0
    
    while True:
        
        if len(s) == 1 and s[0] == '1':
            break
        
        z_cnt += s.count('0')
        s = s.replace("0", "")
        num = len(s)
        
        arr = []
        while num != 0:
            arr.append(str(num%2))
            num = num//2
        
        arr.reverse()
        s = ''.join(arr)
        cnt += 1
    
    answer.append(cnt)
    answer.append(z_cnt)
    
    
    return answer
  • At first, the while statement in the binary conversion part within the while statement was written as while num//2 != 0:, but then when only 1 remained at the end, 1 was not included and the loop ended due to a condition.
    • Therefore, change the condition to num != 0
  • Also, at first, when reverse sorting, I wrote it as arr.sort(reverse=True), but if I write it that way, the order is broken because it just sorts from the largest number.
    • Therefore, arr.reverse() allows the remainder to be stacked upside down.
  • At first, an error occurred because s = arr was used to assign the created arr to s, making it a list rather than a string.
    • To solve the problem, you can save it as a string through s = '',join(arr).
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
def solution(s):

    z_cnt = 0

    cnt = 0

    

    while s != "1":

        z_cnt += s.count("0")

        s = s.replace("0", "")

        

        num = len(s)

        s = bin(num)[2:]

        

        cnt += 1

    

    return [cnt, z_cnt]

It can also be written in the same way as above.

  • bin() function
    • Python function that converts a number into a string in binary form ex) bin(10) -> Changes to '0b1010' (0b in front indicates a binary number)

    • In the above code, only the binary part is needed, so cut out the part that indicates a binary number, such as bin(10)[2:].