-2

I am trying to set the output formatting but not getting the relevant code portion.

The task:

Given an integer, , print the following values for each integer from to :

  • Decimal
  • Octal
  • Hexadecimal (capitalized)
  • Binary
  • Function Description

Complete the print_formatted function in the editor below.

print_formatted has the following parameters:

  • int number: the maximum value to print

Prints

The four values must be printed on a single line in the order specified above for each from to . Each value should be space-padded to match the width of the binary value of and the values should be separated by a single space.

Input Format

A single integer denoting .

Constraints

Sample Input

17

Sample Output

    1     1     1     1
    2     2     2    10
    3     3     3    11
    4     4     4   100
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8    10     8  1000
    9    11     9  1001
   10    12     A  1010
   11    13     B  1011
   12    14     C  1100
   13    15     D  1101
   14    16     E  1110
   15    17     F  1111
   16    20    10 10000
   17    21    11 10001

Below is the code I wrote in python:

def print_formatted(number):
    # your code goes here
    for n in range(1, number+1):
        print(n, str(oct(n))[2:].upper(), str(hex(n))[2:].upper(), str(bin(n))[2:].upper(), sep=" ")

if __name__ == '__main__':
    n = int(input())
    print_formatted(n)

It is working but formatting is missing and not accepted as solution.

error

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • It looks like when you copy-pasted the task, some math notation went missing. Here for example: `integer, , print the following values for each integer from to :` It looks like that should be something like ``integer, `number`, print the following values for each integer from `1` to `number+1`:`` – wjandrea Mar 12 '22 at 23:24

1 Answers1

0

You can use padding in formatting syntax (Check: Format Specification Mini-Language)

def print_formatted(number):
    formats = "doXb"  # d - decimal, o - octal, X - hexadecimal, b - binary
    padding = number.bit_length()  # length of number in binary
    for i in range(1, number + 1):
        for fmt in formats:
            print(f"{i:{padding}{fmt}}", end=" ")
        print()  # new line

Usage:

print_formatted(17)

Output:

    1     1     1     1 
    2     2     2    10 
    3     3     3    11 
    4     4     4   100 
    5     5     5   101 
    6     6     6   110 
    7     7     7   111 
    8    10     8  1000 
    9    11     9  1001 
   10    12     A  1010 
   11    13     B  1011 
   12    14     C  1100 
   13    15     D  1101 
   14    16     E  1110 
   15    17     F  1111 
   16    20    10 10000 
   17    21    11 10001 
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35