2013-08-06 28 views
-2

嘿所有在stackoverflow! 我正在學習python,需要編寫一個程序來檢查一個數字是否是自傳式的。 EG: 21200是自傳式的,因爲它有2個0,1個2個2個0個3個和0個4個。這是我到目前爲止有:python的自傳體數字?

# Autobiographical numbers 
a = input("Number: ") 
abn = 
if a == abn: 
    print(a, "is autobiographical") 
else: 
    print(a, "is not autobiographical") 

,你可以看到我已經離開了荷蘭的可變開,因爲我不知道究竟是如何做到這一點。我想我已經確定與LEN的長度(a),然後使用類似

[x[::1] for x in b] 

,但我不太清楚,因爲我很新的蟒蛇。 謝謝, python的no0b。

+3

查看http://rosettacode.org/wiki/Self-describing_numbers –

回答

1

我使用下面的代碼來測試它。應該有更好的解決方案。

from collections import Counter 
def test(x): 
    if len(x) > 10: 
      return False 
    c = Counter(x) 
    for i, v in enumerate(x): 
      if int(v) != c.get(str(i), 0): 
        return False 
    return True 

a = input('number: '): #2.x use raw_input 
if test(a): 
    print(a, 'is') 
else: 
    print(a, 'is not') 

演示:

>>> auto 
['1210', '2020', '21200', '3211000', '42101000'] 
>>> map(test, auto) 
[True, True, True, True, True] 

>>> auto = ['12321', '13213', '134', '1231', '123124543'] 
>>> map(test, auto) 
[False, False, False, False, False] 

從維基更好的解決方案:

>>> def isSelfDescribing(n): 
     s = str(n) 
     return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) 
+0

感謝所有回覆!我喜歡你們所有人的幫助,我很欣賞這個網站的鏈接。我給了zhangyangyu第一選擇,因爲他告訴我如何在Python 3中獲得所需的輸出。謝謝! – NoviceProgrammer

0
import math 

b = int(math.log(a,10)) 

*b is length of a. i.e., number of digits in a* 

*in fact there is another tick:* 

b = len(str(a)) 

*of course you need to check if a is a valid natural number* 
1

正如梅德said,Rosettacode有答案:Self-describing numbers

def isSelfDescribing(n): 
    s = str(n) 
    return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) 

我的解決方案將是以下(儘管是慢):

from collections import Counter 
def isAutobiographical(n): 
    digits = map(int, str(x)) 
    actualFrequency = Counter(digits) 
    claimedFrequency = dict((x,y) for x,y in enumerate(digits) if y > 0) 
    return actualFrequency == claimedFrequency 
0
>>> def is_autobiographical(n): 
    s = str(n) 
    count_digits = ''.join([str(s.count(str(i))) for i in range(len(s))]) 
    return s == count_digits 

>>> is_autobiographical(21200) 
True 
>>> is_autobiographical(22) 
False 

你的情況,你可以使用abn = ''.join([str(str(a).count(str(i))) for i in range(len(str(a)))])滿足您的需求。