2015-10-25 189 views
1

我想「圓圓」數值的有序列表,這可以在(正極/負極)浮動或整數形式。我不想在輸出中使用相同的值,除非輸入值本身是相同的。我將理想像四捨五入到最接近的5或10,在幅度可能的最高水平進行,並且降下來,直到在相鄰值之間的不匹配。回合Python列表具有唯一值

以下是一些例子就是我在尋找:

[-0.1, 0.21, 0.29, 4435.0, 9157, 9858.0, 10758.0, 11490.0, 12111.9]

結果:

[-0.1, 0.0, 0.25, 5000.0, 9000.0, 10000.0, 11000.0, 11500.0, 12000.0]

這是我到目前爲止有:

def rounder(n, base=1): 
    base = base * (10 ** (len(str(abs(n))) - len(str(abs(n))))) 
    return base * round(float(n)/base) 

for i in range(len(inp_values)-1): 
    while True: 
     a = rounder(inp_values[i], 10**((len(str(abs(int(inp_values[i])))))-(i+1))/2) 
     b = rounder(inp_values[i+1], 10**((len(str(abs(int(inp_values[i+1])))))-(i+1))/2) 
     print a, b 
     if a < b: 
      break 

任何幫助將b非常感謝。

+1

你能解釋一下'0.21 - > 0.0'? –

+0

如果它轉到'0.25',那麼結果將與它的右邊相同。 – user1185790

+0

這是否有真實世界的用例? – uselpa

回答

1

如果你讓你圓潤號碼字典(前一輪=鍵,道道=值),並寫了四捨五入使用精度要求不高,如果舍入的值將在字典碰撞循環?例如:

from math import log10, floor 

def roundSD(x, sd): 
    "Returns x rounded to sd significant places." 
    return round(x, -int(floor(log10(abs(x)))) + sd - 1) 

def round5(x, sd): 
    "Returns x rounded to sd significant places, ending in 5 and 0." 
    return round(x * 2, -int(floor(log10(abs(x)))) + sd - 1)/2 




inputData = [-0.1, 0.21, 0.29, 4435.0, 9157, 9858.0, 10758.0, 11490.0, 12111.9] 
roundedDict = {} 
roundedData = [] 

for input in inputData: 
    if input in roundedDict: 
     # The input is already calculated. 
     roundedData.append(roundedDict[input]) 
     continue 

    # Now we attempt to round it 
    success = False 
    places = 1 
    while not success: 
     rounded = roundSD(input, places) 
     if rounded in roundedDict.values(): 
      # The value already appeared! We use better precision 
      places += 1 
     else: 
      # We rounded to the correct precision! 
      roundedDict[input] = rounded 
      roundedData.append(rounded) 
      success = True 

這將保證如果兩個數字相同,它們會給出相同的舍入輸出。如果兩個數字不同,他們將永遠不會給出相同的輸出。

運行從上面給出:

[-0.1, 0.2, 0.3, 4000.0, 9000.0, 10000.0, 11000.0, 11500.0, 12000.0]

隨意輪函數更改爲自己納入輪僅5 & 10。

+0

工程就像一個魅力。謝謝!我不太確定這個答案的理由是什麼。如果可能的話,你能解釋一下我怎麼可能只是5秒和10秒? – user1185790

+1

嗯,我認爲目前的答案看起來很整齊,但如果你堅持,檢查出的替代功能全面上面我補充道。請注意,4435仍然不會達到5000,因爲4500距離更近。 –