Starting from:
$35

$29

Problem #1 Subject: Printing a large integer with thousands separators (commas).

Modules: none

Filename: discrete_math.py

Humans have difficulty correctly interpreting long strings of uninterrupted numbers, which is why we use separators to group digits within a number. In English-speaking countries, the usual convention is to use a comma to separate the whole-number portion of a number into groups of three (and, hence, known as the ‘thousands separator’. For example, the value 12345 is written as 12,345.

Since we will be working with relatively large numbers (a 64-bit number contains 19 or 20 digits), we want to be able to print them with thousands separators such that 9223372036854775808 = 9,223,372,036,854,775,808

Write a function, named pretty_int(n), that takes a single argument, assumed to be a non-negative integer, and returns a string representing that number and that includes the comma separators.

Place this function in the discrete_math module and include test code that prints out the values, 0, 1, 999, 1000, 2^16, and 2^64 using your pretty_int() function.

Your test code should ONLY execute if the module is run directly; it should NOT execute if the module is imported by another script.

HINT: This is NOT a hard problem – it can be done in five lines of code, but it requires a bit of planning. There are also multiple ways to go about it, some decidedly more elegant than others, but any way that works is acceptable. Also, don’t let yourself get bogged down with this. If nothing else, start off with a function that merely returns the number converted to a string, move on, and accept the hit.

WORK

The pretty_int function in the module converts a non-negative integer into a string representation with thousands separators. It takes an integer `n` as input and returns a string with commas inserted for thousands. The function is implemented using Python's built-in string formatting method. In the main code block, it is tested whether the pretty_int function is implemented. If it is not implemented, a message is printed indicating that the function is not available. Otherwise, a list of integers is iterated over, and for each integer in the list, its string representation with thousands separators is printed.

OUTPUT

discrete_math.py : pretty_int() test

0 = 0

1 = 1

999 = 999

1000 = 1,000

65536 = 65,536

18446744073709551616 = 18,446,744,073,709,551,616