簡體   English   中英

如何去除尾隨零的整數

[英]How to strip integers of trailing zeros

給定一組整數(例如{1000000, 20000000, 1234000, 1200000} ),我想將 function 應用於所有這些整數:

  1. 盡可能降低一個數的大小
  2. 所有數字仍然是整數
  3. 它們的相對比例保持不變

換句話說,我想去除盡可能多的零而不丟失絕對量級以外的任何信息,因此集合將變為{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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM