Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Write a function that simulates three cubic dice rolls.

Hi, I want to write a function that simulates three cubic dice rolls. In case the same number is drawn twice in a row, display "Double!" Example: Input: random () Output: 2 5 5 Double!

I already wrote the randomizing function... but I am not sure how to finish it... Thanks in advance for your help!

import random
i=0
list =[]
def randomizer():
  for i in range (3):
   i+=1
   list.append(random.randrange(0,6))

  return(list)

print(randomizer())   
Will Berlanga
Will Berlanga
18,825 Points

Now you need to evaluate the list for duplicate occurrences in a row of the number. This would require checking the first and second number, and then check the second and third number.

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,732 Points

Maybe something like this?

import random

def hand_randomizer(number_of_dice=3, number_of_sides=6):
    """randomize a hand"""
    # optionally specify number of dice, and number of sides per dice
    # default is 3 for number_of_dice
    # default is 6-sided dice
    hand = []
    for i in range(number_of_dice):
        hand.append(random.randint(1,number_of_sides))
    return(hand)

def match_count(value, hand):
    """return how many dice match the give value"""
    count = 0
    for die in hand:
        if die == value:
            count += 1
    return count

def max_matching_values(hand):
    """return maximum number of matching dice"""
    for count in range(len(hand),0,-1):
        for die in hand:
            if match_count(die, hand) == count:
                return count
    return 0

# create a hand
hand = hand_randomizer()
# count maximum number of matching dice
max_match = max_matching_values(hand)

output = str(hand)
if max_match == 2:
    output += " Double!"
if max_match == 3:
    output += " Three-of-a-kind!"

print(output)

Example output of three selected runs

[4, 1, 5]
[1, 1, 6] Double!
[4, 4, 4] Three-of-kind!