""" File: diceOutcomes.py Description: Rolls two dice a user specified number of times to determine the outcome(s) with the highest percentage. """ from random import randint def main(): """ Main program provides an outline of program """ numberOfRolls, dieSides = displayWelcomeAndInputRolls() mostFrequentRolls, highestCount = calculateFrequentRolls(numberOfRolls, dieSides) displayResults(numberOfRolls, dieSides, mostFrequentRolls, highestCount) def displayWelcomeAndInputRolls(): """ Displays welcome message for the user and returns the number of rolls and number of sides on each die. """ print "This programs rolls two dice many times to determine the", \ "outcome(s) with the highest frequency.\n" numberOfRolls = input("Enter the number of times to roll the dice: ") dieSides = input("Enter the number of sides on each die: ") print return numberOfRolls, dieSides def calculateFrequentRolls(numberOfRolls, dieSides): """Rolls the dice the correct number of times, tallies the outcomes, and returns a list of outcomes with highest counts and highest count.""" # initialize outcomeCounts to all 0s. The index corresponds to the outcome # NOTE: index positions 0 and 1 are not possible outcomeCounts = [] for count in range(dieSides*2+1): outcomeCounts.append(0) rollAndTallyOutcomes(numberOfRolls, dieSides, outcomeCounts) print "outcomeCounts:",outcomeCounts # For debugging highestCount = max(outcomeCounts) mostFrequentRolls = findOutcomes(outcomeCounts, highestCount) print "mostFrequentRolls:", mostFrequentRolls, \ "and highestCount:",highestCount # For debugging return mostFrequentRolls, highestCount def rollAndTallyOutcomes(numberOfRolls, dieSides, outcomeCounts): """Rolls the dice the correct number of times and tallies the outcomes in the outcomeCounts list of tallies with the index being the outcome.""" for rollNumber in range(numberOfRolls): outcome = randint(1,dieSides) + randint(1,dieSides) outcomeCounts[outcome] += 1 def findOutcomes(outcomeCounts, highestCount): """Returns a list of outcomes with the highest count.""" highestOutcomesList = [] for outcome in range(2,len(outcomeCounts)): if outcomeCounts[outcome] == highestCount: highestOutcomesList.append(outcome) return highestOutcomesList def displayResults(numberOfRolls, dieSides, mostFrequentRolls, highestCount): """ Displays the outcome(s) with the highest percentage""" print "This programs rolls two %d-sided dice %d times to" \ % (dieSides, numberOfRolls) print "determine the outcome(s) with the highest percentage." print resultStr = "The highest percentage is %3.1f" % (highestCount*100.0/numberOfRolls) \ + "% for outcome(s): " for index in range(len(mostFrequentRolls)): resultStr += str(mostFrequentRolls[index])+ " " print resultStr main()