Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
The storage report lists every partition with its size in bytes, which means comparing two partitions involves counting digits. The team wants the same numbers rendered in binary units, the way every file browser does it, so an oversized partition is obvious without arithmetic.
Write human_bytes(size, precision=1). Return the formatted string, or None when the input is not a size.
Function to write
human_bytes(size: int | float, precision: int = 1) -> str | NoneThe size rendered in binary units, such as 1.5 KiB, or None when the input is not a number.
How to approach it
Divide while the value is large enough and there is still a bigger unit to move into.
Sample cases
+ 2 held back until you submit
a file listing
Fifteen hundred bytes is one and a half kibibytes, so the unit has to step up once.
Input
Argument 1
1536Returns
'1.5 KiB'an empty file
Zero bytes stays in bytes and shows no decimal point at all.
Input
Argument 1
0Returns
'0 B'a large partition
Two and a half gibibytes, stepping up three units and honouring the requested precision.
Input
Argument 1
2684354560Argument 2
2Returns
'2.5 GiB'a size that is not one
A size that is not a number returns None rather than a formatted string of nonsense.
Input
Argument 1
'12 MB'Returns
None
Constraints
B, KiB, MiB, GiB, TiB, PiB.PiB. A size past the largest unit shows a large number in PiB rather than inventing a unit.B shows no decimal point; every larger unit is rounded to precision decimal places.None.0 B.Worked example
1536 bytes is one and a half kibibytes. The loop divides once, leaves 1.5 and stops, because dividing again would put the value below one and 0.0 MiB tells a reader nothing. The rule is 'the largest unit that keeps the value at or above one', and it is what makes two sizes comparable by eye.
The condition on the loop is the part that gets written wrong. Stopping only when the value drops below 1024 works until the value is larger than the biggest unit you have — then the index runs off the end of the unit list and the function raises on the one file anybody was worried about. Bound the loop by the units as well as by the value.
What this tests
A loop with two termination conditions, and the discipline of deciding what happens past the end of your own table of units. Formatting looks trivial until the boundary case is the one you were reporting on.
human_bytes(size: int | float, precision: int = 1) -> str | NoneSubmit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.