Feb-21-2021, 06:06 PM
(Feb-21-2021, 04:09 PM)new_coder_231013 Wrote: I'm trying to learn Python and am currently about halfway through an introductory book inAlso as new user you should not use Python 2.7,which as of Jan 2020 is officially dead💀
Code will give errors on
print
and has_key(removed)
in Python 3. So if fix indentation and write code so it work for Python 3.9 it look like this.
from random import randint frequency = {} for i in range(1000): num = randint(1, 10) if num in frequency: frequency[num] = frequency[num] + 1 else: frequency[num] = 1 print(frequency)Also a alternative is to use collections defaultdict as it's made for these kind of task.
import collections from random import randint frequency = collections.defaultdict(int) for i in range(1000): frequency[randint(1, 10)] += 1 print(frequency)
Output:defaultdict(<class 'int'>, {7: 99, 3: 98, 2: 98, 1: 105, 8: 92, 9: 103, 5: 111, 10: 101, 4: 106, 6: 87})
Can throw in Counter,to get most common.>>> from collections import Counter >>> >>> d = Counter(frequency) >>> d.most_common(3) [(5, 111), (4, 106), (1, 105)] >>> d.most_common(1) [(5, 111)]