【问题标题】:How to strip integers of trailing zeros如何去除尾随零的整数
【发布时间】:2020-02-06 04:40:27
【问题描述】:

给定一组整数(例如{1000000, 20000000, 1234000, 1200000}),我想对它们都应用一个函数:

  1. 尽可能降低数字的大小
  2. 所有数字都是整数
  3. 它们的相对比例保持不变

换句话说,我想去除尽可能多的零而不丢失绝对幅度以外的任何信息,因此集合将变为{1000, 20000, 1234, 1200}

这个操作是否有一个术语,是否有一个高效的 Python 函数,或者我应该快速编写代码吗?

编辑:This solution 不是重复的,因为它处理单数 - 在我的情况下,零的数量取决于特定的集合。

编辑 2:Green Cloak Guy 为我的确切要求提供了一个解决方案,而 Illmora 提供了一个我应该首先真正概念化的解决方案。

【问题讨论】:

标签: python function integer


【解决方案1】:

查看您的要求,您可以通过将每个输入数字除以所有输入数字的 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 的特性,保证输出是最小可能的整数,仍然保持每个数字之间的相对比例。

【讨论】:

  • 是的,这就是困扰我的实际方法!谢谢!
【解决方案2】:

鉴于您在这里关心的只是减少幅度,您是否考虑过将您的数字表示为Decimals,然后以科学记数法打印?

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 的基数,因此您必须找出自己的解决方案。

【讨论】:

  • 所以没有现有的方法,那么 - 非常感谢您花时间提供完整的解决方案!
【解决方案3】:

如果有更有效的方法,请不要惊叹。我会使用:

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]

【讨论】:

    【解决方案4】:

    不那么温和,但它有效。

    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]
    

    【讨论】:

      【解决方案5】:

      以防万一您不担心集合元素的顺序。

       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}
      

      【讨论】:

        【解决方案6】:

        没有嵌套循环或两个包含一些工作的循环

        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)
        

        【讨论】:

          猜你喜欢
          • 2021-10-15
          • 1970-01-01
          • 1970-01-01
          • 2014-09-02
          • 2011-11-01
          • 1970-01-01
          • 2021-12-04
          • 2011-05-30
          • 1970-01-01
          相关资源
          最近更新 更多