Reputation: 3
Well, firstly, hi there. I don't believe this has appeared yet, so correct me if it has.
I am creating a dice rolling simulator that returns the frequency of the numbers rolled as well as the numbers rolled. You can input the amount of sides and amount of rolls. Good starter project, so I've been told. I'm using count() to count the amount of times each number appears on the list.
That's where it gets a bit off.The highest value in the list has one less than it should, for example:
You have a 6 sided die, and you roll it 6 times. You get 1, 2, 3, 4, 5 and 6. When it displays occurrences it would display all but the highest value as 1. It says that six appears 0 times.
Here's the code slab:
a.sort()
topvalue = a.pop()
while topvalue >= 0:
y = a.count(topvalue)
print topvalue, "appears", y< "times."
topvalue = topvalue-1
if topvalue == -1:
break
Going back to my example, due to the way this was coded, if six truly didn't appear, it wouldn't even be printed, but it is. Hope you and your python wisdom can help!
Upvotes: 0
Views: 163
Reputation: 20391
To get the last element here, instead of:
topvalue = a.pop()
do:
topvalue = a[-1] # This represents the last index.
This is because pop()
actually removes the last element, hence the one-off error.
Although as an idea, in your position I would do:
from collections import Counter
amounts = Counter(a)
for item, num in amounts.items():
print('{0} occurred {1} times'.format(item, num))
Upvotes: 2