2017-02-09 34 views
1

爲了優化一行代碼,我試圖在我的代碼中編寫一個確定的語句,而不用調用任何函數或方法。當我想到這個時,我想知道這對我來說甚至是可能的。我正在尋找一些關於這方面的信息,但它似乎很少,但在我目前的工作中,我必須能夠保持代碼完整,除了優化部分。 希望你能幫我一把。歡迎任何幫助。寫一個語句而不調用任何函數?

這是我目前的進展。

def count_chars(s): 
'''(str) -> dict of {str: int} 

    Return a dictionary where the keys are the characters in s and the values 
    are how many times those characters appear in s. 

    >>> count_chars('abracadabra') 
    {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1} 
    ''' 
    d = {} 

    for c in s: 
     if not (c in d): 
      # This is the line it is assumed to be modified without calling function or method 
     else: 
      d[c] = d[c] + 1 

    return d 
+2

位中的剩餘部分代碼,你* *隱式調用了一堆的方法。例如'__iter__'在'for'循環中被調用。 –

+0

您是否記得C語言中的三元運算符? –

+0

'print({letter:word.count(letter)for set(word)})''或者使用.count()違反了你的規則? – Keatinge

回答

0

這個怎麼樣,因爲在評論中提到,它隱含的使用功能,但我認爲這可能是那種你正在尋找的東西?

s='abcab' 
chars={} 
for char in s: 
    if char not in chars: 
     chars[char]=0 
    chars[char]+=1 

結果

{'a': 2, 'b': 2, 'c': 1}