I m试图缩小一组数字,以输入DP子集-总算法。 (如果数字太大,就会打击。) 具体来说,我需要找到10人的最大力量,能够在不失去精确性的情况下将人数分成几个部分。 我的工作是例行的,但由于工作往往在 lo中进行,我希望工作比我所介绍的简陋武力方法更快。 我的数字是 Dec。
from decimal import Decimal
import math
def largest_common_power_of_10(numbers: list[Decimal]) -> int:
"""
Determine the largest power of 10 in list of numbers that will divide into all numbers
without losing a significant digit left of the decimal point
"""
min_exponent = float( inf )
for num in numbers:
if num != 0:
# Count the number of trailing zeros in the number
exponent = 0
while num % 10 == 0:
num //= 10
exponent += 1
min_exponent = min(min_exponent, exponent)
# The largest power of 10 is 10 raised to the min_exponent
return int(min_exponent)
decimal_numbers = [Decimal("1234"), Decimal("5000"), Decimal("200")]
result = largest_common_power_of_10(decimal_numbers)
assert(result == 0)
decimal_numbers = [Decimal(470_363_000.0000), Decimal(143_539_000.0000), Decimal(1_200_000.0000)]
result = largest_common_power_of_10(decimal_numbers)
assert(result == 3)
divisor = 10**result
# Later processing can use scaled_list
scaled_list = [x/divisor for x in decimal_numbers]
assert(scaled_list == [Decimal( 470363 ), Decimal( 143539 ), Decimal( 1200 )])
reconstituted_list = [x * divisor for x in scaled_list]
assert(reconstituted_list == decimal_numbers)