[英]How to strip integers of trailing zeros
给定一组整数(例如{1000000, 20000000, 1234000, 1200000}
),我想将 function 应用于所有这些整数:
换句话说,我想去除尽可能多的零而不丢失绝对量级以外的任何信息,因此集合将变为{1000, 20000, 1234, 1200}
是否有此操作的术语,是否有有效的 Python function,或者我应该快速编写代码?
编辑: 这个解决方案不是重复的,因为它处理单数 - 在我的例子中,零的数量取决于特定的集合。
编辑 2:Green Cloak Guy 为我的确切要求提供了一个解决方案,而 Illmora 提供了一个我应该首先真正概念化的解决方案。
查看您的要求,您可以通过将每个输入数字除以所有输入数字的 GCD(最大公分母)来轻松完成您所追求的目标。
#!/usr/bin/env python3
import math
from functools import reduce
numbers = [1000000, 20000000, 1234000, 1200000]
# Find the greatest common denominator
gcd = reduce(lambda x,y: math.gcd(x,y), numbers)
# Divide each number by the GCD
minimum_numbers = map(lambda x: int(x/gcd), numbers)
print(*minimum_numbers, sep=',')
使用您的输入数字,它会产生以下结果:
500,10000,617,600
由于 GCD 的特性,output 保证是最低的 integer 仍然保持每个数字之间的相对比例。
鉴于您在这里关心的只是减少幅度,您是否考虑过仅将您的数字表示为Decimal
s,然后以科学记数法打印它们?
from decimal import Decimal
nums = {Decimal(1000000), Decimal(20000000), Decimal(1234000), Decimal(1200000)}
print({str(num.normalize()) for num in nums})
# {'1E+6', '1.2E+6', '2E+7', '1.234E+6'}
如果这对您的用例不合理,那么您可以做的另一件事基本上是确定您可以减少的最大幅度,然后减少那么多。 对于 10 的数量级,这相当简单,您可以使用字符串来执行此操作:
nums = {1000000, 20000000, 1234000, 1200000}
div_factor = 10 ** min(len(str(num)) - len(str(num).rstrip('0')) for num in nums)
reduced_nums = {num / div_factor for num in nums}
# {1000.0, 1234.0, 20000.0, 1200.0}
# you can use integer division `//` instead of true division `/` if you want
对于非标准量级(例如 3 级),您需要更有创意并想出一种方法来有效地计算出您可以除以的最大量级。 我上面的例子通过检查当我们去掉尾随的零时有多少数字消失(这相当于检查可以整数除以数字的 10 的最大指数)来采取捷径。 由于 python 没有内置的方法来打印不是 2、8、10 或 16 的碱基,因此您必须找出自己的解决方案。
如果有更有效的方法,不要kwow。 我会使用:
import numpy as np
def reduce(array):
mult = [0.1]*len(array)
while all(item%10 == 0 for item in array):
array = np.multiply(array, mult)
return array
结果:
intgrs = (1000000, 20000000, 1234000, 1200000)
print(reduce(intgrs))
它将返回具有以下值的 numpy 数组:[1000 20000 1234 1200]
不是那么温和,但它有效。
def trim_zeros(nums):
while 1:
for i in nums:
if str(i)[-1] != "0":
return(nums)
nums=[int(i/10) for i in nums]
以防万一您不担心集合元素的顺序。
sets = {1000000, 20000000, 1234000, 1200000}
max = max([len("".join(map(str, str(i))).rstrip('0')) for i in sets])
new_set = {int(str(i)[:max]) for i in sets} # gives {1000, 1234, 1200, 2000}
没有嵌套循环或两个包含一些工作的循环
from numpy import multiply
intgr = [1000000, 20000000, 1234000, 1200000]
total = str( sum(intgr) )
mgntd = 10 ** ( len(total) - len(total.rstrip('0') ))
reslt = multiply(intgr, [1/mgntd]*len(intgr)).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.