Weisen Pan 4ec0a23e73 Edge Federated Learning for Improved Training Efficiency
Change-Id: Ic4e43992e1674946cb69e0221659b0261259196c
2024-09-18 18:39:43 -07:00

39 lines
2.1 KiB
Python

# -*- coding: utf-8 -*-
# @Author: Weisen Pan
from collections.abc import Iterable
# Define a function named 'clever_format' that takes two arguments:
# 1. 'nums' - either a single number or a list of numbers to format.
# 2. 'fmt' - an optional string argument specifying the format for the numbers (default is "%.2f", meaning two decimal places).
def clever_format(nums, fmt="%.2f"):
# Check if the input 'nums' is not an instance of an iterable (like a list or tuple).
# If it is not iterable, convert the single number into a list for uniform processing later.
if not isinstance(nums, Iterable):
nums = [nums]
# Create an empty list to store the formatted numbers.
formatted_nums = []
# Loop through each number in the 'nums' list.
for num in nums:
# Check if the number is greater than 1 trillion (1e12). If so, format it by dividing it by 1 trillion and appending 'T' (for trillions).
if num > 1e12:
formatted_nums.append(fmt % (num / 1e12) + "T")
# If the number is greater than 1 billion (1e9), format it by dividing by 1 billion and appending 'G' (for billions).
elif num > 1e9:
formatted_nums.append(fmt % (num / 1e9) + "G")
# If the number is greater than 1 million (1e6), format it by dividing by 1 million and appending 'M' (for millions).
elif num > 1e6:
formatted_nums.append(fmt % (num / 1e6) + "M")
# If the number is greater than 1 thousand (1e3), format it by dividing by 1 thousand and appending 'K' (for thousands).
elif num > 1e3:
formatted_nums.append(fmt % (num / 1e3) + "K")
# If the number is less than 1 thousand, simply format it using the provided format and append 'B' (for base or basic).
else:
formatted_nums.append(fmt % num + "B")
# If only one number was passed, return just the formatted string for that number.
# If multiple numbers were passed, return a tuple containing all formatted numbers.
return formatted_nums[0] if len(formatted_nums) == 1 else tuple(formatted_nums)