P ython p rogramming e xercises


Exercise #37: Change Maker



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə122/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   116   117   118   119   120   121   122   123   124
PythonProgrammingExercisesGentlyExplained

Exercise #37: Change Maker 
def makeChange(amount): 
# Create a dictionary to keep track of how many of each coin: 
change = {} 
# If the amount is enough to add quarters, add them: 
if amount >= 25: 


Python Programming Exercises, Gently Explained 
149 
change['quarters'] = amount // 25 
# Reduce the amount by the value of the quarters added: 
amount = amount % 25 
# If the amount is enough to add dimes, add them: 
if amount >= 10: 
change['dimes'] = amount // 10 
# Reduce the amount by the value of the dimes added: 
amount = amount % 10 
# If the amount is enough to add nickels, add them: 
if amount >= 5: 
change['nickels'] = amount // 5 
# Reduce the amount by the value of the nickels added: 
amount = amount % 5 
# If the amount is enough to add pennies, add them: 
if amount >= 1: 
change['pennies'] = amount 
return change 
Exercise #38: Random Shuffle 
# Import the random module for its randint() function. 
import random 
def shuffle(values): 
# Loop over the range of indexes from 0 up to the length of the list: 
for i in range(len(values)): 
# Randomly pick an index to swap with: 
swapIndex = random.randint(0, len(values) - 1) 
# Swap the values between the two indexes: 
values[i], values[swapIndex] = values[swapIndex], values[i] 
Exercise #39: Collatz Sequence 
def collatz(startingNumber): 
# If the starting number is 0 or negative, return an empty list: 
if startingNumber < 1: 
return [] 
# Create a list to hold the sequence, beginning with the starting number: 
sequence = [startingNumber] 
num = startingNumber 
# Keep looping until the current number is 1: 
while num != 1: 
# If odd, the next number is 3 times the current number plus 1: 
if num % 2 == 1: 
num = 3 * num + 1 
# If even, the next number is half the current number: 
else: 
num = num // 2 
# Record the number in the sequence list: 
sequence.append(num) 
# Return the sequence of numbers: 
return sequence 


Python Programming Exercises, Gently Explained 
150 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   116   117   118   119   120   121   122   123   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