Python Programming Exercises, Gently Explained
140
return None
# Dictionary with keys of numbers and values of how often they appear:
numberCount = {}
# Track the most frequent number and how often it appears:
mostFreqNumber = None
mostFreqNumberCount = 0
# Loop through all the numbers, counting how often they appear:
for number in numbers:
# If the number hasn't appeared before, set it's count to 0.
if number not in numberCount:
numberCount[number] = 0
# Increment the number's count:
numberCount[number] += 1
# If this is more frequent than the most frequent number, it
# becomes the new most frequent number:
if numberCount[number] > mostFreqNumberCount:
mostFreqNumber = number
mostFreqNumberCount = numberCount[number]
# The function returns the most frequent number:
return mostFreqNumber
Exercise #17: Dice Roll
# Import the random module for its randint() function.
import random
def rollDice(numberOfDice):
# Start the sum total at 0:
total = 0
# Run a loop for each die that needs to be rolled:
for i in range(numberOfDice):
# Add the amount from one 6-sided dice roll to the total:
total += random.randint(1, 6)
# Return the dice roll total:
return total
Dostları ilə paylaş: