简体   繁体   English

如何去除尾随零的整数

[英]How to strip integers of trailing zeros

Given a set of integers (eg {1000000, 20000000, 1234000, 1200000} ), I want to apply to all of them a function such that:给定一组整数(例如{1000000, 20000000, 1234000, 1200000} ),我想将 function 应用于所有这些整数:

  1. the magnitude of a number is lowered as far as possible尽可能降低一个数的大小
  2. all numbers remain integers所有数字仍然是整数
  3. their relative proportions remain constant它们的相对比例保持不变

In other words, I want to strip as many zeros as possible without losing any information other than absolute magnitude, so the set would become {1000, 20000, 1234, 1200}换句话说,我想去除尽可能多的零而不丢失绝对量级以外的任何信息,因此集合将变为{1000, 20000, 1234, 1200}

Is there a term for this operation and is there an efficient Python function, or should I just quickly code this?是否有此操作的术语,是否有有效的 Python function,或者我应该快速编写代码?

Edit: This solution is not a duplicate because it deals with singular numbers - in my case, the number of zeros depends on the particular set.编辑: 这个解决方案不是重复的,因为它处理单数 - 在我的例子中,零的数量取决于特定的集合。

Edit 2: Green Cloak Guy provided a solution for my exact requirements, and Illmora one that does what I should have actually conceptualized in the first place.编辑 2:Green Cloak Guy 为我的确切要求提供了一个解决方案,而 Illmora 提供了一个我应该首先真正概念化的解决方案。

Looking at your requirements, what you are after can be easily done by dividing each input number by the GCD (Greatest Common Denominator) of all the input numbers.查看您的要求,您可以通过将每个输入数字除以所有输入数字的 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=',')

With your input numbers, it produces this result:使用您的输入数字,它会产生以下结果:

500,10000,617,600

Because of the properties of the GCD, the output is guaranteed to be the lowest possible integer that still maintains the relative proportions between each number.由于 GCD 的特性,output 保证是最低的 integer 仍然保持每个数字之间的相对比例。

Given all you care about here is decreasing magnitude, have you considered just representing your numbers as Decimal s and then printing them in scientific notation?鉴于您在这里关心的只是减少幅度,您是否考虑过仅将您的数字表示为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'}

If that's not reasonable for your use case, then another thing you can do is essentially determine the maximum magnitude you can reduce by, and then reduce by that much.如果这对您的用例不合理,那么您可以做的另一件事基本上是确定您可以减少的最大幅度,然后减少那么多。 For magnitudes of 10, this is fairly simple and you can use strings to do it:对于 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

For nonstandard magnitudes (eg magnitudes of 3), you'd need to get more creative and come up with a way to efficiently figure out the largest magnitude you can divide by.对于非标准量级(例如 3 级),您需要更有创意并想出一种方法来有效地计算出您可以除以的最大量级。 My example above takes a shortcut here by checking how many digits disappear when we cut out the trailing zeroes (which is equivalent to checking the largest exponent of 10 that can be integer-divided into the number).我上面的例子通过检查当我们去掉尾随的零时有多少数字消失(这相当于检查可以整数除以数字的 10 的最大指数)来采取捷径。 Since python doesn't have a built-in way to print in bases that aren't 2, 8, 10, or 16, you'll have to figure out your own solution.由于 python 没有内置的方法来打印不是 2、8、10 或 16 的碱基,因此您必须找出自己的解决方案。

Don't kwow if there's a more efficient way.如果有更有效的方法,不要kwow。 I would use:我会使用:

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

Results:结果:

intgrs = (1000000, 20000000, 1234000, 1200000)
print(reduce(intgrs))

It will return a numpy array with the following values: [1000 20000 1234 1200]它将返回具有以下值的 numpy 数组:[1000 20000 1234 1200]

Not so gentle, but it works.不是那么温和,但它有效。

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]

Just in case you don't worry about the ordering of the set elements.以防万一您不担心集合元素的顺序。

 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}

not have nested loop or two loop which contain some work没有嵌套循环或两个包含一些工作的循环

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM