2016-02-28 57 views
-3

我試圖從一個元組中獲取第100個整數。現在的問題有云:從一個元組獲取第100個整數(python)

Implement a function get_hundredth(a, b, c) that takes in 3 positive integers as arguments and returns a tuple of digits at the respective hundredth position.

If a given integer is less than 100, its hundredth position can be viewed as 0. If the input is invalid, return None for that integer.

get_hundredth(1234, 509, 80633) should return (2, 5, 6) and get_hundredth(4024, 81, 2713) should return (0, 0, 7)

這是我到目前爲止有:

def get_hundredth(a, b, c): 

    a, b, c = str(a), str(b), str(c) 

    return int(a[-3:-2]), int(b[-3:-2]), int(c[-3:-2]) 

我怎麼讓它爲0,如果是100下?

+3

我想你混淆「百分之一」與「數百名」 –

+0

如果被「噓」,你會返回「b」。那真的好嗎? – hruske

回答

1

由於其他的答案,沒有解決的時候返回None問題...

def get_hundredth(a,b,c): 
    def hundreds(x): 
     try: 
      return (x // 100) % 10 if (isinstance(x, int) and x > 0) else None 
     except TypeError: 
      return None 
    return tuple(map(hundreds, (a,b,c))) 

print(get_hundredth(1234, 509, 80633)) # (2, 5, 6) 
print(get_hundredth(-89, 81.85, 'test')) # (None, None, None) 
+0

不,實際上我沒有。好點子。 – Alexander

+0

@Alexander,儘管「無效」輸入也可能是負數。我做了適當的編輯 –

+0

錯過了,謝謝(雖然它似乎暗示整數的錯誤可能是負面的)。那麼所有其他不是整數的數字類型呢?它們是有效的還是無效的(你假設有效)。 – AChampion

0

這將爲一個整數返回所需的值:

def _get_hundreds(a): 
    return (a % 1000)/100 

放棄一切,但最後3位數字(% 1000),然後得到hudreds(/ 100)。 對於3的整數:

def get_hundreds(a, b, c): 
    return map(_get_hundreds, (a, b, c)) 
1

如果需要數百然後使用mod%)運算符,如:

h = x // 100 % 10 

所以對於你的函數看起來像(更新的錯誤處理):

def get_hundredth(a, b, c): 
    return tuple(x//100 % 10 if isinstance(x, int) and x > 0 else None for x in (a, b, c)) 
0

Python 2解決方案:

def get_hundredth(a, b, c): 
    return [i/100 % 10 for i in [a, b, c]] 

>>> get_hundredth(1234, 509, 80633) 
[2, 5, 6] 

>>> get_hundredth(4024, 81, 2713) 
[0, 0, 7] 
+0

如果它們中的任何一個是無效的,例如。不能被100整除? – hruske

+0

當值爲81時,最後一個示例返回0。您記住什麼值? – Alexander

+0

這假定整數除法(應該真的使用'//強制使用它,並且在python3中是正確的),如果i <100,x // 100等於0,如果> 100則丟棄任何小數部分。應該真的返回一個'tuple' 。 – AChampion

0
def get_hundredth(*k): 
    return map(lambda x: x/100 % 10, k) 

這不會糾錯,但它會讓您更接近您的解決方案。由於您對所有參數進行相同的操作,因此可以將它們作爲列表(k),然後將map應用於所有參數。

相關問題