The Little Book of Algorithms



Yüklə 1,84 Mb.
Pdf görüntüsü
səhifə4/4
tarix28.11.2023
ölçüsü1,84 Mb.
#168110
1   2   3   4
The Little Book of Algorithms

exam
rather than each student, the 
outer for loop will be for each 
exam. 
Remember to reset the total 
after each iteration of the inner loop. 


44 
Write a subprogram that takes the 2D list of exam results as an 
argument and outputs the mean average for each student. 
Hint: Remember to reset the total to 0 after outputting the average 
for each student 
cs_scores = [["Karman","45","60","72"], 
["Daniel","55","65","70"],
["Giacomo","71","78","78"],
["Jessica","68","79","80"],
["Edie","98","85","91"]]
def mean_student( ):


45 
Write a function which takes in 1 hexadecimal digit as an argument 
and returns the denary equivalent.
Write a main function which asks the user to input a hexadecimal 
value and then passes this value to the function you have written.
Hint: Pages 7 and 20


46 
The size of a sound file can be calculated by using the following 
formula:
File size = sampling frequency * bit depth * channels * duration 
The answer will be given in bits, therefore we can convert this to 
kilobytes by dividing the answer by (8 * 1024.) 
Write a subprogram which takes the sampling frequency, bit depth, 
channels and duration of a sound file and returns the file size. This 
can then be outputted in Kilobytes and Megabytes. 


47 
Use the space below to finish the function and to show how it may 
be called. 


48 


49 


50 


51 


52 


53 
Eirini Kolaiti came up with the great idea of putting example solutions to 
the challenges at the back of the book. I will also post these solutions 
online at: http://bit.do/LBOA 
There is always more than one way to solve a problem. Even if the 
algorithm is well-defined, there may be alternative programming 
approaches. The following pages present examples which you can 
compare to your own answers. Comments have been provided to aid your 
understanding, you should develop the habit of commenting all your 
programs. 
Do not worry if you have written an alternative solution. Also be aware 
that these solutions were not produced by typing the whole program out 
and running them with no syntax and logic errors on the first time! There 
was a debugging process as I wrote each line or block of code. 
Encountering errors whilst iteratively testing is the “normal” way to 
develop programs.
#define a function called highest_num with three parameters
def highest_number (num1, num2, num3): 
# return the highest number
if num1 >= num2 and num1 >= num3: 
return num1 
elif num2 >= num1 and num2 >= num3: 
return num2 
else: 
return num3 
first = int(input("Enter the first number: ")) 
second = int(input("Enter the second number: ")) 
third = int(input("Enter the third number: ")) 
# call the highest_number function and pass the contents of
# first, second and third variables as arguments into the
# parameters num1, num2, num3 
highest = highest_number(first,second,third) 
#output the highest number with a meaningful message 
print("The highest number is " + str(highest))


54 
def generate_username (firstname, lastname): 
# create username based on the lastname and first intiial 
username = lastname + firstname[0] 
# open the file in read mode and evaluate its contents
users_file = open("users.txt","r") 
usernames = eval(users_file.read()) 
users_file.close() 
# check the entire 2D array to see if the username exists
for count in range(len(usernames)): 
# if the username exists, add a # symbol
if usernames[count][0] == username: 
username = username + "#" 
# return the final username 
return username 
forename = input("Enter your first name: ") 
surname = input("Enter your surname: ") 
username_out = generate_username(forename, surname) 
print("Your username is " + str(username_out))
def cuboid_volume (length, width, height): 
volume = length * width * height 
return volume 
length_in = int(input("Enter the length of the cuboid: ")) 
width_in = int(input("Enter the width of the cuboid: ")) 
height_in = int(input("Enter the height of the cuboid: ")) 
volume_out = cuboid_volume(length_in, width_in, height_in) 
print("The volume of the cuboid is " + str(volume_out))


55 
import random 
# initialise the dice with two different values so the
# program runs at least once 
dice1 = 1 
dice2 = 2 
while dice1 != dice2: 
dice1 = random.randint(1,6) 
dice2 = random.randint(1,6) 
print("Dice 1 rolled:" + str(dice1)) 
print("Dice 2 rolled:" + str(dice2)) 
if dice1 == dice2: 
print("Game loading") 
else: 
# Use input to enable the user to press enter to continue 
# looping
again = input("Press enter to roll again") 


56 
def vowel_counter(sentence): 
A = 0 
E = 0 
I = 0 
O = 0 
U = 0 
for count in range(len(sentence)): 
# The .upper() casts the current letter to an upper 
case 
# Without .uppper(), we would write 
# if sentence[count] == "A" or sentence[count] == 
"a": 
if sentence[count].upper() == "A": 
A = A+1 
elif sentence[count].upper() == "E": 
E = E+1 
elif sentence[count].upper() == "I": 
I = I+1 
elif sentence[count].upper() == "O": 
O =O+1 
elif sentence [count].upper() == "U": 
U = U+1 
# using comma to concatenate in Python means we can cast
# the integer values implicitly without using str() 
print("The number of A's:", A) 
print("The number of E's:", E) 
print("The number of I's:", I) 
print("The number of O's:", O) 
print("The number of U's:", U) 
sentence = "Learning programming is similar to learning a 
musical instrument. Both involve practise and making lots of 
mistakes. Both also require perseverence to develop fluency. 
Keep going!" 
vowel_counter(sentence) 


57 
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54] 
highest = numbers[0] 
for count in range(len(numbers)): 
if highest < numbers[count]: 
highest = numbers[count] 
print("The highest number is", highest) 
# An alternative approach using a function: 
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54] 
def highest_num(numbers_in): 
highest = numbers[0] 
for count in range(len(numbers)): 
if highest < numbers[count]: 
highest = numbers[count] 
return highest 
highest_out = highest_num(numbers) 
print("The highest number is", highest_out) 
obvious = ["password", "qwerty", "hello123", "letmein", 
"123456"] 
password = input("Please enter a password: ") 
# A basic linear search which iterates through the obvious 
# list to check for matches against the password 
for count in range(len(obvious)): 
if password == obvious[count]: 
print("This password is weak. It uses a common word or \ 
phrase making it susceptible to a brute force attack") 
# Length check 
if len(password) < 8: 
print("Your password is too short. Please use at least \ 
8 characters") 


58 
# initialise some counter variables for different types of
# characters 
char = 0 
num = 0 
upper = 0 
lower = 0 
for count in range(len(password)): 
# A linear search to check if the character is a digit 
if password[count].isdigit(): 
num = num+1 
# A check to see if the character is an upper or lower char
elif password[count].isalpha(): 
char = char+1 
if password[count].isupper(): 
upper = upper+1 
elif password[count].islower(): 
lower = lower+1 
if num == 0: 
print("To make your password more secure, you could include \ 
numbers") 
if upper == 0 or lower ==0: 
print("To make your password more secure, you could include \ 
upper and lower case letters") 
if char == 0: 
print("To make your password more secure, you could include \ 
letters") 
if num > 0 and char > 0 and upper > 0 and lower > 0: 
print("Your password meets the minimum length requirements \ 
and contains a mixture of numbers, characters, upper and lower 
case letters.") 
def marks(grade_in): 
grades = [["A*","90"],["A","83"],["B","72"],["C","60"],
["D","49"],["E","30"]] 
for count in range(len(grades)): 
if grades[count][0] == grade_in: 
return grades[count][1] 
grade = input("What grade do you wish to achieve") 
mark_req = marks(grade) 
print("For grade", grade, "you need to gain", mark_req) 


59 
import random 
keeper = ["left", "centre", "right"] 
keeper_score = 0 
player_score = 0 
for count in range(5): 
dive = random.choice(keeper) 
player = input("Do you wish to shoot to the left, centre or 
right: ") 
print("Keeper went to the", dive) 
if keeper == player: 
print("Penalty saved") 
keeper_score = keeper_score+1 
else: 
print("GOAAAAAAL!") 
player_score = player_score+1 
if keeper_score > player_score: 
print("Keeper wins", keeper_score, "-", player_score) 
else: 
print("You win!", player_score, "-", keeper_score) 
def new_user(username_in, password_in): 
users_file = open("users.txt", "r")
users = eval(users_file.read())
users_file.close() 
new_user = [] 
new_user.append(username_in)
new_user.append(password_in)
users.append(new_user) 
users_file = open("users.txt", "w")
users_file.write(str(users))
users_file.close()


60 
def mean_of_list(numbers_list_in): 
total = 0 
for count in range(len(numbers_list_in)): 
total = total + numbers_list_in[count] 
# divide by the length of the list to find the mean
average = total / len(numbers_list_in) 
return average 
def main(): 
numbers_list = [0,7,5,3,22,23,11,34,51,32,5,3,1] 
mean = mean_of_list(numbers_list) 
print("The mean average of", numbers_list, "=", mean) 
main()
# A better way to call main in case the file is imported: 
# if __name__ == '__main__': 
# main() 
cs_scores=[["Karman","45","60","72"], 
["Daniel","55","65","70"], 
["Giacomo","71","78","78"], 
["Jessica","68","79","80"], 
["Edie","98","85","91"]] 
total = 0 
for exam in range(1,4): 
# iterate through each exam 
for student in range(len(cs_scores)): 
# update the total by iterating through each student
total = total + int(cs_scores[student][exam]) 
# calculate the total
print("Total for exam num", exam, "=", total) 
# reset the total before starting on the next exam
total = 0 


61 
cs_scores=[["Karman","45","60","72"],["Daniel","55","65","70"], 
["Giacomo","71","78","78"],["Jessica","68","79","80"], 
["Edie","98","85","91"]] 
def mean_student(scores_in): 
total = 0 
for exam in range(1,4): 
# iterate through each exam
for student in range(len(cs_scores)): 
# update the total by iterating through each student
total = total + int(cs_scores[student][exam]) 
# calculate and output the mean
mean = total / len(cs_scores) 
print("Mean average for exam num", exam, "=", mean) 
# reset the total before starting on the next exam 
total = 0 
mean_student(cs_scores) 
def hex_to_denary(hex_in): 
# only convert values A to F
hex_A_to_F = [["A","10"],["B","11"],["C","12"],["D","13"],
["E","14"],["F","15"]] 
convert = False 
for count in range(len(hex_A_to_F)): 
if hex_in == hex_A_to_F[count][0]: 
convert = True 
return int(hex_A_to_F[count][1]) 
# if values are not A to F i.e. 1 to 9, return these as
# integers 
if convert == False: 
return int(hex_in) 
def main(): 
hexi = input("Enter a hex digit to convert: ") 
hex_out = hex_to_denary(hexi) 
print("The denary equivalent is", hex_out) 


62 
def file_size(frequency, bits, channels, duration): 
size = frequency * bits * channels * duration 
return size 
def main(): 
freq = int(input("Enter the frequency in Hz: ")) 
bit_depth = int(input("Enter the bit depth: ")) 
channel = int(input("Enter the number of channels: ")) 
length = int(input("Enter the duration of the sound file in \
seconds: ")) 
size_out = file_size(freq, bit_depth, channel, length) 
size_kb = size_out / (8 * 1024) 
size_mb = size_kb / 1024 
print("The file size is", size_kb, "KB") 
print("The file size is", size_mb, "MB") 
main()
# A better way to call main in case the file is imported: 
# if __name__ == '__main__': 
# main() 


63 
¹Two brilliant books for absolute beginners. These “how-to” guides take you step by step 
through the basic programming structures required to access most of the material in this 
book. 
Coding Club Python Basics Level 1 (2012) ¹ 
Coding Club Next Steps Level 2 (2013) 
Chris Roffey 
Making Games with Python and Pygame (2012) 
Automate The Boring Stuff With Python (2015) 
www.inventwithpython.com 
Al Sweigart 
www.pythonprogramming.net 
See also: Youtube channel- sentdex 
Sentdex 
www.kidscancode.org 
See also: Youtube channel- KidsCanCode 
Chris and Priya 
Bradfield
Youtube channel– MrLauLearning 
William Lau 
Youtube channel– Tech With Tim 
Tech With Tim 
Youtube channel- Corey Schafer 
Corey Schafer 
Youtube channel– Computerphile 
Computerphile 
How We Learn (2014) 
Benedict Carey 
Why We Sleep (2017) 
Matthew Walker 
Teaching Computing in Secondary Schools 
William Lau 
Computer Science Education 
Edited by Sue Sentance, 
Erik Barendsen and 
Carsten Schulte 
Teach Like a Champion 2.0 
Doug Lemov 
Tools for Teaching 
Fred Jones 


64 
My knowledge and understanding of programming was initially developed 
by attending courses run by Ilia Avroutine, Darren Travi, Graham 
Bradshaw, David Batty and Sarah Shakibi. I have also benefitted greatly 
from the mentoring of Merijn Broeren, Elizabeth Hidson and Andy Swann.
The generosity of those who produce resources to teach programming 
such as Chris Roffey, Al Sweigart and Sentdex along with the wider CAS 
and Facebook community is also a great source of inspiration. To all of 
the aforementioned, I am indebted. You have given me the confidence to 
keep developing my programming skills independently and to eventually 
share these skills with you on CAS, Facebook, Youtube and in my books. 

To further my understanding of programming, I have had the great 
privilege of sharing thoughts with Peter Kemp, Alex Parry, Eirini Kolaiti, 
Richard Pawson, Scott Portnoff, Sue Sentance and Meg Ray. All of these 
brilliant teachers and programmers read early drafts of this book and 
their comments have improved the book significantly.
I hope that my compromise of including procedures as well as non-
modular programs is forgiven. I have to be realistic and acknowledge that 
for all novices, writing programs without subroutines is a starting point 
and an achievement in itself. There are many solutions to a given 
algorithm and provided that the output is correct and the algorithm is 
reasonably efficient, we should recognise these as correct (up to GCSE 
level) even if subroutines are not used. 
I thank my colleagues, particularly Lloyd Stevens, Leila Lassami, Jaime 
Vega, Gavin Tong, Edward Swire, Pat Cronin and Jamie Brownhill at 
Central Foundation Boys’ School (CFBS). They have supported me with 
their time, patience and agreeable responses to my (occasionally 
unreasonable) demands! I also thank the students at CFBS whose hard 
work have provided me with further motivation to improve my teaching . 
Our students always inspire us to be better .
To Suki, Zi and Q, this book would not be possible without you. Many 
people ask me how I have time to write these books and my answer is, “I 
have an understanding family!” Thank you for your continued support. 


65 


Have you ever wanted to become more fluent at Python programming? 
Perhaps you find the prospect of file writing or using 2D data structures 
daunting? If so, then this is the book for you!
The Little Book of Algorithms concisely presents sixteen problems which 
computer science students will commonly encounter. These problems are 
solved efficiently using programs written using Python. However, reading 
these programs is not enough, so the second half of the book presents 
you with some challenges so that you can apply what you have learnt.
After finishing this book, you should feel more familiar with: 
• While loops and For loops 
• Concatenating different data types 
• Using procedures and functions 
• Working with 1D and 2D lists and arrays 
• File reading and writing
This book will show you how to write better Python programs and will 
expose you to the key skills that are required to do well in any 
programming assignment or exam. 

Yüklə 1,84 Mb.

Dostları ilə paylaş:
1   2   3   4




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