This is a college homework. I have to simulate 10 random dice rolls (between 1 - 6) and put them in a list, then create another list which will keep the amount of times each value was rolled. My output has to be like this:
Your rolls: [6, 2, 3, 4, 5, 6, 3, 1, 5, 2]
Number of rolls:
1 -> 1
2 -> 2
3 -> 2
4 -> 1
5 -> 2
6 -> 2
This is how my code turned out:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = []
print(f"Your rolls: {rolls}")
print("Number of rolls:")
rolls.sort()
for i in rolls:
# Puts the amount of times each number (1-6) rolled inside roll_count
roll_count.append(rolls.count(i))
# Removes the duplicates so that the count doesn't register again
while rolls.count(i) > 1:
rolls.remove(i)
for n in range(1, 7):
# Checks if the possible rolls (1-6) have been rolled, if not place the count as 0
# in the sorted index inside roll_count
if n not in rolls:
roll_count.insert(n - 1, 0)
print(f"{n} -> {roll_count[n - 1]}")
It works properly, but I wanted to know if I could make it more efficient or even simplify it.
CodePudding user response:
The standard tool for this kind of task is a collections.Counter
, from the standard library. It is purpose-built for precisely this task.
from collections import Counter
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = Counter(rolls)
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n]}")
Your rolls: [2, 5, 3, 3, 3, 2, 5, 5, 2, 6]
Number of rolls:
1 -> 0
2 -> 3
3 -> 3
4 -> 0
5 -> 3
6 -> 1
If for some reason you're not allowed to use collections.Counter()
, your implementation is just about as good as it can be, with one exception - a dict
is a better datastructure to use than a list
for the roll count (indeed, collections.Counter
is a subclass of dict
). This enables you to use the setdefault()
and get(key, default)
, which cuts out a few lines of code:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
roll_count = {}
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in rolls:
roll_count.setdefault(i, 0) # does nothing if element is already present
roll_count[i] = 1
for n in range(1, 7):
print(f"{n} -> {roll_count.get(n, 0)}")
CodePudding user response:
from random import randint
rolls = []
roll_count = [0] * 6
for i in range(10):
r = randint(1,6)
rolls.append(r)
roll_count[r-1] = roll_count[r-1] 1
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for n in range(1, 7):
print(f"{n} -> {roll_count[n - 1]}")
Instead of looping once to form a rolls list and then loop once again to count each one, you can do this way to loop once and roll as well as count in the same loop. And you don't need to sort as well or check if a count exists or not.
CodePudding user response:
from random import randint
rolls = [randint(1, 6) for _ in range(10)]
print(f"Your rolls: {rolls}")
print("Number of rolls:")
for i in range(1,7):
print(f"{i} -> {rolls.count(i)}")