Task 1: Thousand Separator
"Comma Chameleon: Making Numbers Readable!"
This week's first task involves formatting numbers with thousand separators. Given a positive integer, we need to add commas as thousand separators and return the result as a string. This is a common formatting requirement for displaying large numbers in a human-readable format.
The Strategy: We reverse the string representation of the number, then use regex to insert commas every three digits from the right. Finally, we reverse the string back to get the properly formatted number. This approach handles numbers of any length efficiently.
Perl Implementation
sub thousand_separator ($int) {
($int) = $INT_CHECK->($int);
die 'Expected a positive integer' if $int <= 0;
my $s = reverse "$int";
$s =~ s/(\d{3})(?=\d)/$1,/g;
return scalar reverse $s;
}
Python Implementation
def thousand_separator(value: int) -> str:
"""Format positive integer with commas as thousands separators."""
if value <= 0:
raise ValueError("Expected a positive integer")
s = str(value)[::-1]
parts = [s[i : i + 3] for i in range(0, len(s), 3)]
return ",".join(part[::-1] for part in parts[::-1])