2

I am fairly new to programming and have been working on a program to count the number of times every value from 0-9 occurs in a string of numbers (this program must use a function and main function that calls it). If a user enters the numbers 123512378, I want it to tell me 1 occurs 2 times 2 occurs 2 times... 8 occurs 1 time etc. Right now I am trying to pass a string into a function then return a list with the number of occurrences in order. However mine just returns the empty list I generated at the start. Here is my code:

def countdigits(aString,Result):
  countValue=0
  while countValue>=9:
    Result[countValue]=(aString.count(str(countValue)))
    countValue=countValue+1
  return Result

def main():
  emptyList = 10 * [0]
  numbers=str(input("Pleas enter a string of numbers: "))
  print(countdigits(numbers,emptyList))

main()
4

2 に答える 2

3

を使用しwhile countValue<=9:ます。を使用しました>=

于 2012-10-31T17:46:29.557 に答える
1

代わりにあなたはただ使うことができます

for i in range(10): 
    Result[i]=(aString.count(str(i)))

または単に

return [aString.count(str(i)) for i in range(10)]

しかし、これは非常に非効率的な方法のように見えます(以下の編集を参照)。10回ループしています(aString.countは文字列全体を検索する必要があります)が、1回ループしてカウントするだけでカウントできます。

import collections
def countdigits(aString):
  count_map = collections.defaultdict(int)
  for c in aString:
      count_map[c] += 1
  return count_map

print countdigits("123456789")

出力:

defaultdict(<type 'int'>, {'1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '7': 1, '6': 1, '9': 1, '8': 1})

必要に応じて、次のように簡単に配列に変換できますがResult、その利点はわかりません。

編集:2番目のバージョンは1回ループするので高速である必要があるように見えますが、そうではなく、list.countCであり、超高速で高速検索を実行しますが、Pythonでのループは遅すぎるため、timeitは誰が本当の勝者であるかを示します

import collections

def countdigits1(aString):
    return [aString.count(str(i)) for i in range(10)]

def countdigits2(aString):
    count_map = collections.defaultdict(int)
    for c in aString:
        count_map[c] += 1
    return count_map

import timeit
text = "0123456789"*10
print timeit.timeit('countdigits1("%s")'%text, setup="from __main__ import countdigits1", 
                    number=10000)
print timeit.timeit('countdigits2("%s")'%text, setup="from __main__ import countdigits2", 
                    number=10000)

出力:

0.106333017349
0.952333927155

2番目のバージョンは9倍以上遅くなります。

于 2012-10-31T18:30:19.863 に答える