P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə114/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   110   111   112   113   114   115   116   117   ...   124
PythonProgrammingExercisesGentlyExplained

Exercise #15: Median 
def median(numbers): 
# Special case: If the numbers list is empty, return None: 
if len(numbers) == 0: 
return None 
# Sort the numbers list: 
numbers.sort() 
# Get the index of the middle number: 
middleIndex = len(numbers) // 2 
# If the numbers list has an even length, return the average of the 
# middle two numbers: 
if len(numbers) % 2 == 0: 
return (numbers[middleIndex] + numbers[middleIndex - 1]) / 2 
# If the numbers list has an odd length, return the middlemost number: 
else: 
return numbers[middleIndex] 
Exercise #16: Mode 
def mode(numbers): 
# Special case: If the numbers list is empty, return None: 
if len(numbers) == 0: 


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 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   110   111   112   113   114   115   116   117   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin