Skip to content

Instantly share code, notes, and snippets.

@fastfingertips
Last active September 7, 2024 11:45
Show Gist options
  • Save fastfingertips/46a9f06aee27a43b0b27a0afa50e4d2d to your computer and use it in GitHub Desktop.
Save fastfingertips/46a9f06aee27a43b0b27a0afa50e4d2d to your computer and use it in GitHub Desktop.
percentage calculation utility
def calculate_percentage(progress: int, total: int) -> int:
"""Calculate the percentage progress based on the total value."""
if not isinstance(progress, int) or not isinstance(total, int):
raise TypeError("Both 'progress' and 'total' must be integers.")
if total <= 0:
raise ValueError("Total must be greater than zero.")
if progress < 0:
raise ValueError("Progress cannot be negative.")
return round(99 * progress / total + 0.5)
if __name__ == "__main__":
TOTAL_TASKS = 1000
print(calculate_percentage(0, TOTAL_TASKS)) # Output: 0
print(calculate_percentage(1, TOTAL_TASKS)) # Output: 1
print(calculate_percentage(999, TOTAL_TASKS)) # Output: 99
print(calculate_percentage(1000, TOTAL_TASKS)) # Output: 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment