Reputation: 715
Can anyone explain this code a little. I can't understand what n
does here? We already have taken N = int(input())
as input then why n=len(bin(N))-2
? I couldn't figure it out.
N = int(input())
n = len(bin(N))-2
for i in range(1,N+1):
print(str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n))
Upvotes: 0
Views: 50
Reputation: 1121206
n
counts the number of bits in the number N
. bin()
produces the binary representation (zeros and ones), as as string with the 0b
prefix:
>>> bin(42)
'0b101010'
so len(bin(n))
takes the length of that output string, minus 2 to account for the prefix.
See the bin()
documentation:
Convert an integer number to a binary string prefixed with “0b”.
The length is used to set the width of the columns (via str.rjust()
, which adds spaces to the front of a string to create an output n
characters wide). Knowing how many characters the widest binary representation needs is helpful here.
However, the same information can be gotten directly from the number, with the int.bitlength()
method:
>>> N = 42
>>> N.bit_length()
6
>>> len(bin(N)) - 2
6
The other columns are also oversized for the numbers. You could instead calculate max widths for each column, and use str.format()
or an f-string to do the formatting:
from math import log10
N = int(input())
decwidth = int(log10(N) + 1)
binwidth = N.bit_length()
hexwidth = (binwidth - 1) // 4 + 1
octwidth = (binwidth - 1) // 3 + 1
for i in range(1, N + 1):
print(f'{i:>{decwidth}d} {i:>{octwidth}o} {i:>{hexwidth}X} {i:>{binwidth}b}')
Upvotes: 2