Reputation: 31
so, i wrote this code which first makes a list of 1000 rolls. then i wrote a function which uses dictionaries to have the frequency of every die roll. then i want to print the roll which occurred the most, and its frequency.
import random
L = []
for i in range(1000):
currentRoll = random.randint(1, 6)
L.append(currentRoll)
def diceFreq(L):
rollCount = {}
for roll in L:
if roll not in rollCount:
rollCount[roll] = 1
else:
rollCount[roll] += 1
print(rollCount)
print(max(rollCount, key=rollCount.get))
print(max(rollCount.values()))
diceFreq(L)
i dont understand what exactly print(max(rollCount, key=rollCount.get))
doing in words?
Upvotes: 3
Views: 462
Reputation: 597
I'd recommend that you take advantage of the collections.Counter class, which does all the work of your diceFreq
function in a much more Pythonic manner. It will
So you can replace the entire diceFreq()
defintion with this:
import collections
import operator
print(collections.Counter(L).most_common(1)[0])
Line 3 creates such a Counter from L. You can print this out to verify it has six items, one for each roll. Each item in the dictionary has an associated count, all adding up to 1000. Then it uses the most_common(1)
method to only return the most frequently rolled value and its count. Finally we use the slice [0]
to get the tuple out of the list that most_common()
returned.
Upvotes: 0
Reputation: 1132
Max will receive an iterable and evaluate the max value. I.e:
max([1,2,3]) # >> returns 3
max("abc") # >> returns 'c'
max({"a": 10, "b": 5}) # >> returns 'b'
Your rollCount
is a dict that will iterate through keys by default.
However, when you add a key
to the max function, it will evaluate the value to be considered max
against the callable you set.
I.e:
max([1,2,3], key=lambda x: -x) # >> returns 1
In this case, it will compare the maximum value after sending it to the callable. (1,2,3 would became -1,-2,-3 for the comparison, but will return the original value).
When you call .get
from a dict, it will expect a key
to be passed. when you do this:
d = {"a": 10, "b": 5}
max(d, key=d.get) # returns 'a'
Instead of comparing 'a' >= 'b'
it will do d.get('a') >= d.get('b')
.
d.get('a') # >> 10
d.get('b') # >> 5
Returning in this case 'a'
.
Upvotes: 2