Skip to content

Instantly share code, notes, and snippets.

@NeOneSoft
Created August 30, 2020 02:59
Show Gist options
  • Save NeOneSoft/ab1bfbdff977962d20f3e9ed1a865f7c to your computer and use it in GitHub Desktop.
Save NeOneSoft/ab1bfbdff977962d20f3e9ed1a865f7c to your computer and use it in GitHub Desktop.
Elementary Robotics: Write a function in Python called ‘humanSize’ that takes a non-negative number of bytes and returns a string with the equivalent number of ‘kB’, ‘MB’, ‘GB’, ‘TB’, ‘PB’, ‘EB’, ‘ZB’, or ‘YB’, between [0, 1000), with at most 1 digit of precision after the decimal. If the number of bytes is >= 1000 YB, return this number of YB, …
class HumanSize:
def bytes_converter(self, bases: list, exponents: list) -> list:
return [base / exp for base, exp in zip(bases, exponents)]
def num_Range(self, number: float) -> bool:
return 0 < number < 1000
def humanSize(self, number: int) -> str:
exponents = [10 ** x for x in range(3, 25, 3)]
data = self.bytes_converter([number] * 8, exponents)
units = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
element = [(value, unit) for value, unit in zip(data, units) if self.num_Range(value)]
if element:
return f'{element[0][0]:.1f}{element[0][1]}'
return f'{data[-1]:.1f}{units[-1]}'
# Driver code
conversion = HumanSize()
print(conversion.humanSize(1024))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment